Created
January 16, 2017 07:10
-
-
Save NodoFox/41234609bae68ea259c66b748339542a to your computer and use it in GitHub Desktop.
Find Leaves of Binary Tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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