545. Boundary of Binary Tree

ref:

https://leetcode.com/problems/boundary-of-binary-tree/discuss/101280/Java(12ms)-left-boundary-left-leaves-right-leaves-right-boundary

T: O(n)

S: O(n)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> boundaryOfBinaryTree(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        result.add(root.val); // 1
        
        findLeftBoundary(root.left, result); // 2
        findLeaves(root.left, result); // 3 - find left leaves
        findLeaves(root.right, result); // 3 - find right leaves
        findRightBoundary(root.right, result); // 4
        
        return result;
    }
    
    private void findLeftBoundary(TreeNode node, List<Integer> result) { // 2
        if (node == null || (node.left == null && node.right == null)) {
            return;
        }
        result.add(node.val);
        if (node.left == null) {
            findLeftBoundary(node.right, result);
        } else {
            findLeftBoundary(node.left, result);
        }
    }
    private void findLeaves(TreeNode node, List<Integer> result) { // 3
        if (node == null) {
            return;
        }
        if (node.left == null && node.right == null) {
            result.add(node.val);
        }
        findLeaves(node.left, result);
        findLeaves(node.right, result);
    }
    private void findRightBoundary(TreeNode node, List<Integer> result) { // 3
        if (node == null || (node.left == null && node.right == null)) {
            return;
        }
        if (node.right == null) {
            findRightBoundary(node.left, result);
        } else {
            findRightBoundary(node.right, result);
        }
        result.add(node.val);
    }
}

/*
[1] + [] + [3,4] + [2] = [1,3,4,2].
The boundary of a binary tree is the 

1. concatenation of the root, [1]
2. the left boundary,  []
3. the leaves ordered from left-to-right, [3,4]
4. and the reverse order of the right boundary. [2]
*/

Last updated