程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> 110. Balanced Binary Tree,balancedbinary

110. Balanced Binary Tree,balancedbinary

編輯:JAVA綜合教程

110. Balanced Binary Tree,balancedbinary


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  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     
12     public boolean isBalanced(TreeNode root) {
13       if(root==null)
14       return true;
15       
16       if(DFS(root)==-1)
17       return false;
18       
19       return true;
20       
21     }
22     
23     public int DFS(TreeNode root){
24         int left=1,right=1;
25         if(root.left!=null)
26         {
27             if(DFS(root.left)==-1)
28             return -1;
29             else
30             left=left+DFS(root.left);
31         }
32         if(root.right!=null)
33         {
34             if(DFS(root.right)==-1)
35             return -1;
36             else
37             right=right+DFS(root.right);
38         }
39         
40         if(left-right<-1||left-right>1)
41         return -1;
42         
43         return Math.max(left,right);
44     }
45    
46 }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved