Skip to content

Commit f406012

Browse files
committed
Tree Updates
Tree Updates
1 parent 2baddfe commit f406012

16 files changed

+208
-2
lines changed
907 Bytes
Binary file not shown.
0 Bytes
Binary file not shown.
Binary file not shown.
661 Bytes
Binary file not shown.

bin/chapter6trees/PrintPaths.class

1.39 KB
Binary file not shown.
Binary file not shown.
Binary file not shown.

bin/chapter6trees/WidthOfTree.class

1.05 KB
Binary file not shown.

src/chapter6trees/DiameterOfTree.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,36 @@
1515
package chapter6trees;
1616

1717
public class DiameterOfTree {
18+
public static int diameter = 0;
19+
20+
public int diameterOfTree(BinaryTreeNode root){
21+
int left, right;
22+
if(root == null)
23+
return 0;
24+
left = diameterOfTree(root.getLeft());
25+
right = diameterOfTree(root.getRight());
26+
if(left + right > diameter)
27+
diameter = left + right;
28+
return Math.max(left, right)+1;
29+
}
30+
// Alternative Coding
31+
public int diameter(BinaryTreeNode root){
32+
if(root==null) return 0;
1833

34+
//the path goes through the root
35+
int len1 = height(root.left) + height(root.right) +3;
36+
37+
//the path does not pass the root
38+
int len2 = Math.max(diameter(root.left), diameter(root.right));
39+
40+
return Math.max(len1, len2);
41+
}
42+
public int height(BinaryTreeNode root) {
43+
if(root == null)
44+
return 0;
45+
/* compute the depth of each subtree */
46+
int leftDepth = height(root.getLeft());
47+
int rightDepth = height(root.right);
48+
return (leftDepth > rightDepth) ? leftDepth + 1 : rightDepth + 1;
49+
}
1950
}

src/chapter6trees/FindLevelwithMaxSum.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414

1515
package chapter6trees;
1616

17-
import java.util.ArrayList;
1817
import java.util.LinkedList;
1918
import java.util.Queue;
2019

0 commit comments

Comments
 (0)