File tree Expand file tree Collapse file tree 2 files changed +47
-0
lines changed Expand file tree Collapse file tree 2 files changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for a binary tree node.
3+ * public class TreeNode {
4+ * int val;
5+ * TreeNode left;
6+ * TreeNode right;
7+ * TreeNode() {}
8+ * TreeNode(int val) { this.val = val; }
9+ * TreeNode(int val, TreeNode left, TreeNode right) {
10+ * this.val = val;
11+ * this.left = left;
12+ * this.right = right;
13+ * }
14+ * }
15+ */
16+ class Solution {
17+ public boolean isBalanced (TreeNode root ) {
18+
19+ if (root ==null ){
20+ return true ;
21+ }
22+ else {
23+ int left = height (root .left );
24+ int right = height (root .right );
25+ int diff = left - right ;
26+ diff = diff > 0 ? diff : -diff ; // absolute
27+ if (diff > 1 ){
28+ return false ;
29+ }
30+ return isBalanced (root .left ) && isBalanced (root .right );
31+ }
32+ }
33+
34+ private int height (TreeNode root ){
35+ // calculate the height of a tree
36+ if (root == null ){
37+ return 0 ;
38+ }
39+ else {
40+ int left = height (root .left );
41+ int right = height (root .right );
42+ int height = left > right ? left : right ;
43+ return height + 1 ;
44+ }
45+ }
46+ }
Original file line number Diff line number Diff line change @@ -330,6 +330,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
330330| 1463 | [ Cherry Pickup II] ( https://leetcode.com/problems/cherry-pickup-ii/ ) | [ C++] ( ./C++/Cherry-Pickup-II.cpp ) | _ O(n \* m)_ | _ O(n \* m)_ | Hard | DFS | |
331331| 104 | [ Maximum Depth of Binary Tree] ( https://leetcode.com/problems/maximum-depth-of-binary-tree/ ) | [ python] ( ./Python/maximum-depth-of-binary-tree.py ) | _ O(n)_ | _ O(n)_ | Easy | DFS | |
332332| 112 | [ Path Sum] ( https://leetcode.com/problems/path-sum/ ) | [ Java] ( ./Java/path-sum.java ) | _ O(n)_ | _ O(n)_ | Easy | DFS | |
333+ | 110 | [ Balanced Binary Tree] ( https://leetcode.com/problems/balanced-binary-tree/ ) | [ Java] ( ./Java/Balanced-Binary-Tree.java ) | _ O(n)_ | _ O(n)_ | Easy | DFS | |
333334
334335<br />
335336<div align =" right " >
You can’t perform that action at this time.
0 commit comments