Skip to content

Commit fd09741

Browse files
Update find-leaves-of-binary-tree.java
1 parent f5a5042 commit fd09741

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

find-leaves-of-binary-tree.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,24 @@ else if (root.left == null && root.right == null) {
4848
helper(root, root.right, stack);
4949
}
5050
}
51+
52+
53+
// The second way of using height of node
54+
55+
public static List<List<Integer>> findLeaves(TreeNode root) {
56+
// The height of a node is the number of edges from the node to the deepest leaf
57+
List<List<Integer>> list = new ArrayList<List<Integer>>();
58+
height(root, list);
59+
return list;
60+
}
61+
62+
public static int height(TreeNode node, List<List<Integer>> list) {
63+
if (node == null) return -1;
64+
// the height of leaf is 0
65+
// h(node) = 1 + max(h(node.left), h(node.right))
66+
int level = 1+Math.max(height(node.left, list), height(node.right, list));
67+
if (level >= list.size()) list.add(new ArrayList<Integer>());
68+
list.get(level).add(node.val);
69+
return level;
70+
}
5171
}

0 commit comments

Comments
 (0)