Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✅面试题 04.04. 检查平衡性 #93

Open
Ray-56 opened this issue Aug 19, 2020 · 1 comment
Open

✅面试题 04.04. 检查平衡性 #93

Ray-56 opened this issue Aug 19, 2020 · 1 comment
Labels

Comments

@Ray-56
Copy link
Owner

Ray-56 commented Aug 19, 2020

面试题 04.04. 检查平衡性

题目

实现一个函数,检查二叉树是否平衡。在这个问题中,平衡树的定义如下:任意一个节点,其两棵子树的高度差不超过 1。

示例1:

给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

返回 true

示例2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

         1
        / \
       2   2
     /  \
    3    3
  /  \
 4    4

返回 false

@Ray-56
Copy link
Owner Author

Ray-56 commented Aug 19, 2020

递归解

var isBalanced = function(root) {
    if (root == null) return true;
    
    if (Math.abs(getDepth(root.right) - getDepth(root.left)) > 1) return false;
    return isBalanced(root.left) && isBalanced(root.right);
};

function getDepth(node) {
    if (node == null) return 0;
    return Math.max(getDepth(node.left), getDepth(node.right)) + 1;
}

@Ray-56 Ray-56 added the DFS 深度优先 label Aug 19, 2020
@Ray-56 Ray-56 changed the title 面试题 04.04. 检查平衡性 ✅面试题 04.04. 检查平衡性 Aug 19, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant