zoukankan      html  css  js  c++  java
  • [LeetCode] Balanced Binary Tree

    Question:

    Given a binary tree, determine if it is height-balanced.

    For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

    1、题型分类:

    2、思路:

    3、时间复杂度:

    4、代码:

    import java.util.SortedSet;
    import java.util.TreeSet;
    public class Solution {
        public boolean isBalanced(TreeNode root) {
            if(root==null) return true;
            int leftDepth=depth(root.left);
            int rightDepth=depth(root.right);
            if(Math.abs(leftDepth-rightDepth)>1) return false;
            return isBalanced(root.left)&&isBalanced(root.right);
        }
        public int depth(TreeNode root){  
            if(root==null){  
                return 0;  
            }  
            return 1+Math.max(depth(root.left), depth(root.right));  
        }
    }

    5、优化:

    6、扩展:

  • 相关阅读:
    C++中const变量使用注意
    const对象调用static成员函数
    Error in startup script: value for " " missing
    check tcl version
    socket
    grid pack
    mouse bind
    gesture
    pixel
    open
  • 原文地址:https://www.cnblogs.com/maydow/p/4645227.html
Copyright © 2011-2022 走看看