100. 相同的树
【代码】
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
var isSameTree = function(p, q) {
if(q===null && p===null){
return true
}
if( (q===null || p===null) || q.val !== p.val ) {
return false
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
};
101. 对称二叉树
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isSymmetric = function(root) {
return _isSymmetric(root.left,root.right)
};
function _isSymmetric(left,right){
if(right===null && left===null){
return true
}
if((right===null || left===null) || left.val !== right.val){
return false
}
return _isSymmetric(left.left, right.right) && _isSymmetric(left.right, right.left)
}
104. 二叉树的最大深度
【代码】
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
if(root===null) return 0
return Math.max(maxDepth(root.left), maxDepth(root.right)) +1
};