leetcode Day1

从零开始Leetcode – Day 1

Symmetric Tree

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var isSymmetric = function(root) {
if(root === null){
return true;
}else{
return helper(root.left , root.right);
}
};


function helper(p , q){
if( p === null && q ===null){
return true;
}
if( p === null || q ===null){
return false;
}
if( p.val != q.val){
return false;
}else{
return helper(p.left, q.right) && helper(p.right , q.left);
}
}

Same Tree

1
2
3
4
5
6
7
8
9
10
11
12
var isSameTree = function(p, q) {
if( p === null && q === null){
return true;
}
if( p !== null || q !== null ){
return false;
}
if( p.val != q.val){
return false;
}
return isSameTree( p.left , q.left) && isSameTree( p.right, q.right);
};

Maximum Depth of Binary Tree

1
2
3
4
5
6
7

var maxDepth = function(root) {
if(root === null){
return 0;
}
return Math.max(maxDepth(root.left) , maxDepth(root.right)) + 1;
};

Balanced Binary Tree

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

var isBalanced = function(root) {
if (root === null) {
return true;
}
var leftDepth = maxDepth(root.left);
var rightDepth = maxDepth(root.right);

if (Math.abs(leftDepth - rightDepth) <= 1) {
return isBalanced(root.left) && isBalanced(root.right);
} else {
return false;
}
};

var maxDepth = function (root) {
if (root === null) {
return 0;
}
return Math.max(maxDepth(root.left) ,maxDepth(root.right)) + 1;
};