Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit852fba6

Browse files
balanced binary tree
1 parent7783f3f commit852fba6

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

‎EASY/src/easy/BalancedBinaryTree.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
packageeasy;
2+
3+
importclasses.TreeNode;
4+
5+
publicclassBalancedBinaryTree {
6+
7+
classSolution_1 {
8+
//recursively get the height of each subtree of each node, compare their difference, if greater than 1, then return false
9+
//although this is working, but it's not efficient, since it repeatedly computes the heights of each node every time
10+
//Its time complexity is O(n^2).
11+
publicbooleanisBalanced(TreeNoderoot) {
12+
if(root ==null)returntrue;
13+
if(Math.abs(getH(root.left) -getH(root.right)) >1)returnfalse;
14+
elsereturnisBalanced(root.left) &&isBalanced(root.right);
15+
}
16+
17+
privateintgetH(TreeNoderoot) {
18+
if(root ==null)return0;//base case
19+
intleftH =getH(root.left);
20+
intrightH =getH(root.right);
21+
returnMath.max(leftH,rightH)+1;
22+
}
23+
}
24+
25+
classSolution_2 {
26+
27+
publicbooleanisBalanced(TreeNoderoot) {
28+
if (root ==null)
29+
returntrue;
30+
returngetH(root) != -1;
31+
}
32+
33+
privateintgetH(TreeNoderoot) {
34+
if (root ==null)
35+
return0;
36+
intleftH =getH(root.left);
37+
if (leftH == -1)
38+
return -1;
39+
intrightH =getH(root.right);
40+
if (rightH == -1)
41+
return -1;
42+
if (Math.abs(leftH -rightH) >1)
43+
return -1;
44+
returnMath.max(leftH,rightH) +1;
45+
}
46+
}
47+
48+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp