-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalancedBinaryTree.java
More file actions
75 lines (69 loc) · 1.87 KB
/
Copy pathBalancedBinaryTree.java
File metadata and controls
75 lines (69 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Source : https://leetcode.com/problems/balanced-binary-tree/
// Author : cornprincess
// Date : 2020-08-17
/*****************************************************************************************************
*
* 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 left and right subtrees of every node differ in height by no more than 1.
*
* Example 1:
*
* Given the following tree [3,9,20,null,null,15,7]:
*
* 3
* / \
* 9 20
* / \
* 15 7
*
* Return true.
*
* Example 2:
*
* Given the following tree [1,2,2,3,3,null,null,4,4]:
*
* 1
* / \
* 2 2
* / \
* 3 3
* / \
* 4 4
*
* Return false.
******************************************************************************************************/
package BalancedBinaryTree;
public class BalancedBinaryTree {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
} else {
return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
}
public int height(TreeNode root) {
if (root == null) {
return 0;
} else {
return Math.max(height(root.left), height(root.right)) + 1;
}
}
public boolean isBalanced2(TreeNode root) {
return height2(root) >= 0;
}
public int height2(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = height2(root.left);
int rightHeight = height2(root.right);
if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) {
return -1;
} else {
return Math.max(leftHeight, rightHeight) + 1;
}
}
}