Java O(n) solution. Easy to understand.


  • 0
    B
        public List<Integer> boundaryOfBinaryTree(TreeNode root) {
            List<Integer> res = new ArrayList<>();
            if(root == null) return res;
            res.add(root.val);
            if(root.left != null)left(root.left, res, true);
            if(root.right != null)right(root.right, res, true);
            return res;
        }
        //Add the left boundary nodes in pre-order and leaf nodes 
        private void left(TreeNode n, List<Integer> res, boolean isBoundry)
        {        
            if(n.left == null && n.right == null)
            {
                res.add(n.val);
                return;
            }
            
            if(isBoundry) res.add(n.val);
            if(n.left!= null)left(n.left, res, isBoundry&&true);
            if(n.right!= null)left(n.right, res, isBoundry&&(n.left==null?true:false));
        }
        
        //Add the leaf nodes and right boundary nodes in post-order
        private void right(TreeNode n, List<Integer> res, boolean isBoundry)
        {
            if(n.left == null && n.right == null)
            {
                res.add(n.val);
                return;
            }
            
            if(n.left != null)right(n.left, res, isBoundry&&(n.right==null?true:false));
            if(n.right != null)right(n.right, res, isBoundry&&true);
            if(isBoundry) res.add(n.val);
        }
    

Log in to reply
 

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