Super Intuitive and Concise Java Solution,13ms


  • 0
    public class Solution {
        private List<Integer> res = new ArrayList<>();
        public List<Integer> boundaryOfBinaryTree(TreeNode root) {
            if (root == null) return res;
            res.add(root.val);
            if (root.left != null) getLeft(root.left);
            if (root.left != null || root.right != null) getBottom(root);
            if (root.right != null) getRight(root.right);
            return res;
        }
        private void getLeft(TreeNode root) {
            if (root == null) return;
            if (root.left == null && root.right == null) return;
            res.add(root.val);
            if (root.left != null) getLeft(root.left);
            else getLeft(root.right);
        }
        private void getRight(TreeNode root) {
            if (root == null) return;
            if (root.left == null && root.right == null) return;
            if (root.right != null) getRight(root.right);
            else getRight(root.left);
            res.add(root.val);
        }
        private void getBottom(TreeNode root) {
            if (root == null) return;
            getBottom(root.left);
            if (root.left == null && root.right == null) {
                res.add(root.val);
            }
            getBottom(root.right);
        }
    }
    

Log in to reply
 

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