Verbose java solution. easy to understand


  • 1
    J

    public class Solution {

    private List<Integer> bound = new ArrayList<>();
    
    public List<Integer> boundaryOfBinaryTree(TreeNode root) {
        if (root == null) return bound;
        if (!(root.left == null && root.right == null)) {
            bound.add(root.val);
        }
        TreeNode l = root.left;
        TreeNode r = root.right;
        
        while (l != null && !(l.left == null && l.right == null)) {
            bound.add(l.val);
            if (l.left != null) l = l.left;
            else l = l.right;
        }
        
        Deque<TreeNode> stack = new ArrayDeque<>();
        TreeNode p = root;
        
        while (p != null || stack.size() != 0) {
            if (p != null) {
                stack.add(p);
                if (p.left == null && p.right == null) bound.add(p.val);
                p = p.left;
            }
            else {
                TreeNode tmp = stack.pollLast();
                p = tmp.right;
            }
        }
        
        List<Integer> right = new ArrayList<>();
        while (r != null && !(r.left == null && r.right == null)) {
            right.add(r.val);
            if (r.right != null) r = r.right;
            else r = r.left;
        }
        for (int i = right.size() - 1; i >= 0; i--) {
            bound.add(right.get(i));
        }
        return bound;
    }
    

    }


Log in to reply
 

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