Java One Pass, Short and Easy to understand solution


  • 0
    F
    private boolean leafFound = false;
    
    public List<Integer> boundaryOfBinaryTree(TreeNode root) {
    	List<Integer> res = new ArrayList<>();
    	if (root == null)
    		return res;
    	res.add(root.val);
    	preOrder(root.left, res, true);
    
    	List<Integer> temp = new ArrayList<>();
    	leafFound = false;
    	preOrder(root.right, temp, false);
    
    	for (int i = temp.size() - 1; i >= 0; i--) {
    		res.add(temp.get(i));
    	}
    	return res;
    }
    
    private void preOrder(TreeNode root, List<Integer> res, boolean left) {
    	if (root == null) {
    		return;
    	}
    	if (!leafFound) {
    		res.add(root.val);
    	} else if (root.left == null && root.right == null) {
    		res.add(root.val);
    	}
    
    	if (!leafFound && root.left == null && root.right == null) {
    		leafFound = true;
    	}
    
    	if (left) {
    		preOrder(root.left, res, left);
    		preOrder(root.right, res, left);
    	} else {
    		preOrder(root.right, res, left);
    		preOrder(root.left, res, left);
    	}		
    }

Log in to reply
 

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