File tree Expand file tree Collapse file tree 3 files changed +104
-0
lines changed
LeetCode/Grind169/BinaryTrees Expand file tree Collapse file tree 3 files changed +104
-0
lines changed Original file line number Diff line number Diff line change 1+ package Grind169 .BinaryTrees ;
2+
3+ public class BalancedBinaryTree_110 {
4+ class TreeNode {
5+ int val ;
6+ TreeNode left ;
7+ TreeNode right ;
8+ TreeNode () {}
9+ TreeNode (int val ) { this .val = val ; }
10+ TreeNode (int val , TreeNode left , TreeNode right ) {
11+ this .val = val ;
12+ this .left = left ;
13+ this .right = right ;
14+ }
15+ }
16+ public static void main (String [] args ) {
17+
18+ }
19+
20+ private boolean result = true ;
21+
22+ public boolean isBalanced (TreeNode root ) {
23+ maxDepth (root );
24+ return result ;
25+ }
26+
27+ public int maxDepth (TreeNode root ) {
28+ if (root == null )
29+ return 0 ;
30+ int l = maxDepth (root .left );
31+ int r = maxDepth (root .right );
32+ if (Math .abs (l - r ) > 1 )
33+ result = false ;
34+ return 1 + Math .max (l , r );
35+ }
36+ }
Original file line number Diff line number Diff line change 1+ package Grind169 .BinaryTrees ;
2+
3+ public class InvertBinaryTree_226 {
4+
5+
6+ class TreeNode {
7+ int val ;
8+ TreeNode left ;
9+ TreeNode right ;
10+ TreeNode () {}
11+ TreeNode (int val ) { this .val = val ; }
12+ TreeNode (int val , TreeNode left , TreeNode right ) {
13+ this .val = val ;
14+ this .left = left ;
15+ this .right = right ;
16+ }
17+ }
18+ public static void main (String [] args ) {
19+
20+ }
21+
22+ public static TreeNode invertTree (TreeNode root ) {
23+ TreeNode save = null ;
24+
25+ while (root != null ){
26+ save = root .left ;
27+ root .left = root .right ;
28+ root .right = save ;
29+ invertTree (root .right );
30+ invertTree (root .left );
31+ return root ;
32+ }
33+
34+ return null ;
35+
36+ }
37+ }
Original file line number Diff line number Diff line change 1+ package Grind169 .BinaryTrees ;
2+
3+ public class MaxDepthBinaryTree_104 {
4+ class TreeNode {
5+ int val ;
6+ TreeNode left ;
7+ TreeNode right ;
8+ TreeNode () {}
9+ TreeNode (int val ) { this .val = val ; }
10+ TreeNode (int val , TreeNode left , TreeNode right ) {
11+ this .val = val ;
12+ this .left = left ;
13+ this .right = right ;
14+ }
15+ }
16+
17+ public static void main (String [] args ) {
18+
19+ }
20+
21+ public int maxDepth (TreeNode root ) {
22+ // Base Condition
23+ if (root == null ) return 0 ;
24+ // Hypothesis
25+ int left = maxDepth (root .left );
26+ int right = maxDepth (root .right );
27+ // Induction
28+ return Math .max (left , right ) + 1 ;
29+ }
30+
31+ }
You can’t perform that action at this time.
0 commit comments