File tree 2 files changed +32
-1
lines changed
algorithms/balancedBinaryTree
2 files changed +32
-1
lines changed Original file line number Diff line number Diff line change @@ -301,7 +301,7 @@ LeetCode
301
301
| 114| [ Flatten Binary Tree to Linked List] ( https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ ) | | Medium|
302
302
| 113| [ Path Sum II] ( https://leetcode.com/problems/path-sum-ii/ ) | | Medium|
303
303
| 112| [ Path Sum] ( https://leetcode.com/problems/path-sum/ ) | | Easy|
304
- | 111| [ Minimum Depth of Binary Tree] ( https://leetcode.com/problems/minimum-depth-of-binary-tree/ ) | | Easy|
304
+ | 111| [ Minimum Depth of Binary Tree] ( https://leetcode.com/problems/minimum-depth-of-binary-tree/ ) | [ java ] ( ./algorithms/balancedBinaryTree/Solution.java ) | Easy|
305
305
| 110| [ Balanced Binary Tree] ( https://leetcode.com/problems/balanced-binary-tree/ ) | | Easy|
306
306
| 109| [ Convert Sorted List to Binary Search Tree] ( https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ ) | | Medium|
307
307
| 108| [ Convert Sorted Array to Binary Search Tree] ( https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ ) | | Medium|
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+
3
+ // 自上而下而下递归思路,比较左树与右树高度差
4
+ public boolean isBalanced (TreeNode root ) {
5
+ if (null == root ) {
6
+ return true ;
7
+ }
8
+ int leftDepth = recrusionTreeDepth (root .left , 0 );
9
+ int rightDepth = recrusionTreeDepth (root .right , 0 );
10
+ return Math .abs (leftDepth - rightDepth ) <= 1 && isBalanced (root .left ) && isBalanced (root .right );
11
+ }
12
+
13
+ private int recrusionTreeDepth (TreeNode node , int depth ) {
14
+ if (node == null ) {
15
+ return depth ;
16
+ }
17
+ depth ++;
18
+ int leftDepth = recrusionTreeDepth (node .left , depth );
19
+ int rightDepth = recrusionTreeDepth (node .right , depth );
20
+ return Math .max (leftDepth , rightDepth );
21
+ }
22
+
23
+ //官方给出的计算树的高度的方法
24
+ public int height (TreeNode root ) {
25
+ if (root == null ) {
26
+ return 0 ;
27
+ } else {
28
+ return Math .max (height (root .left ), height (root .right )) + 1 ;
29
+ }
30
+ }
31
+ }
You can’t perform that action at this time.
0 commit comments