加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

110.Balanced Binary Tree

发布时间:2020-12-14 04:15:36 所属栏目:大数据 来源:网络整理
导读: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 .Example 1 :Given the foll
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.
Example 1:
Given the following tree?[3,9,20,null,15,7]:
    3
   /   9  20
    /     15   7
Return true.??Example 2:
Given the following tree?[1,2,3,4,4]:
       1
      /      2   2
    /    3   3
  /  4   4
Return false.





I had this subproblems all  written down. But didn’t’t 
Know how to group them together into code 



2.The second method is based on DFS. Instead of calling depth() explicitly for each child node,we return the height of the current node in DFS recursion. When the sub tree of the current node (inclusive) is balanced,the function dfsHeight() returns a non-negative value as the height. Otherwise -1 is returned. According to the leftHeight and rightHeight of the two children,the parent node could check if the sub tree

class Solution {
    public boolean isBalanced(TreeNode root) {
      return dfs(root) != -1;
        
    }
    private int dfs(TreeNode root){
      if(root == null) return 0;
      



      int left = dfs(root.left);
      if(left == -1) return -1;
// if left subtree is not balanced,return - 1; otherwise it returns a positive number or 0.
      




      int right = dfs(root.right);
      if(right == -1) return -1;
// if right subtree is not balanced,return -1; otherwise it returns a positive number or 0. 


      
      if(Math.abs(left - right) > 1) return -1;
      // if the right subtree and left subtree depth difference is more than 1,return - 1



      return Math.max(left,right) + 1;
// this returns the depth from a root node,which takes the max(left subtree depth,right subtree depth) + 1 


    }
}



This -1 means false,not balanced 

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读