Skip to content

Instantly share code, notes, and snippets.

@NodoFox
Created January 16, 2017 07:10
Show Gist options
  • Save NodoFox/41234609bae68ea259c66b748339542a to your computer and use it in GitHub Desktop.
Save NodoFox/41234609bae68ea259c66b748339542a to your computer and use it in GitHub Desktop.
Find Leaves of Binary Tree
// Find Leaves of Binary Tree
// LeafTraversal
// Concept Problem
//Given a binary tree, find all leaves and then remove those leaves.
// Then repeat the previous steps until the tree is empty.
public List<List<TreeNode>> leafTraversal(TreeNode root) {
if(root == null) return root;
List<List<TreeNode>> leaves = new ArrayList<List<TreeNode>>();
leafTraversalRecurse(root, leaves);
return leaves;
}
private int /*returns level*/ leafTraversalRecurse(TreeNode root, List<List<TreeNode>> leaves) {
if(root == null) return -1; // return -1 for leaf nodes so the level is 0.
int leftLevel = leafTraversalRecurse(root.left, leaves);
int rightLevel = leafTraversalRecurse(root.right, leaves);
int level = Math.max(leftLevel, rightLevel) + 1;
if(level == leaves.size()) { // can be replaced by (level >= leaves.size())
leaves.add(new ArrayList<TreeNode>());
}
leaves.get(level).add(root);
root.left = root.right = null; // remove the leaves
return level;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment