[路飞]算法——二叉树

109 阅读1分钟

100. 相同的树

image.png 【代码】


/**
 * 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. 对称二叉树

image.png


/**
 * 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. 二叉树的最大深度

image.png 【代码】


/**
 * 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
};