My easy AC understanding solution


  • 0
    D

    public class Solution {
    int least = Integer.MIN_VALUE;
    public List<List<Integer>> findLeaves(TreeNode root) {
    List<List<Integer>> res = new ArrayList<>();
    ArrayList<Integer> items = new ArrayList<>();
    while (root != null && root.val!=least) {
    postOrder(items, root);
    if (items.size()>0) {
    res.add(new ArrayList<Integer>(items));
    items.clear();
    }
    clearMarked(root);
    }
    return res;
    }

    private void clearMarked(TreeNode root) {
        if (root != null) {
            clearMarked(root.left);
            clearMarked(root.right);
            if (root.left!=null && root.left.val==least) {
                root.left=null;
            }
            if (root.right!=null && root.right.val==least) {
                root.right = null;
            }
        }
    }
    
    private void postOrder(ArrayList<Integer> items, TreeNode root) {
        if (root != null) {
            postOrder(items, root.left);
            postOrder(items, root.right);
            if (root.left==null && root.right==null) {
                items.add(root.val);
                root.val = least;
            }
        }
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.