Long but easy understanding java code


  • 0
    Y
     public List<List<Integer>> findLeaves(TreeNode root) {
        List<List<Integer>> res = new LinkedList<List<Integer>>();
        if(root == null) return res;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode fakeroot = root;
        while((root.left!=null||root.right!=null)) {
            stack.push(fakeroot);
            List<Integer> tem = new LinkedList<Integer>();
            while(!stack.isEmpty()) {
                TreeNode node = stack.pop();
                if(node.left!=null) {
                    if(node.left.left==null&&node.left.right==null){
                        tem.add(node.left.val);
                        node.left=null;
                    }else{
                        stack.push(node.left);
                    }
                }
                if(node.right!=null) {
                    if(node.right.left==null&&node.right.right==null){
                        tem.add(node.right.val);
                        node.right=null;
                    }else{
                        stack.push(node.right);
                    }
                }
            }
            res.add(tem);
        }
        List<Integer> tem = new LinkedList<Integer>();
        tem.add(root.val);
        res.add(tem);
        return res;
    }

Log in to reply
 

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