leetcode 110. Balanced Binary Tree-平衡二叉树|深度遍历

来源:互联网 发布:帝江网络 编辑:程序博客网 时间:2024/06/08 18:12
原题链接:110.Balanced Binary Tree

【思路】

本题是递归数深度遍历的一种应用。按照题目的意思,对于一个节点分别算出每个节点的左、右子树的深度,如果左、右子树深度差大于1,则可以该树非平衡。那么递归每一个节点,一旦发现某一节点非平衡,就返回false,如果每一节点都平衡,则返回true:

    public boolean isBalanced(TreeNode root) {        if (root == null) return true;        if (Math.abs(getDepth(root.left) - getDepth(root.right)) > 1) return false;        return isBalanced(root.left) && isBalanced(root.right);    }    public int getDepth(TreeNode root) {        if (root == null) return 0;        return Math.max(getDepth(root.left), getDepth(root.right)) + 1;    }
226 / 226 test cases passed. Runtime: 2 ms  Your runtime beats 22.68% of javasubmissions.

1 0
原创粉丝点击