其他分享
首页 > 其他分享> > 545. Boundary of Binary Tree

545. Boundary of Binary Tree

作者:互联网

I have originally write a BFS solution for this problem, but it seems too difficlut.

And then I read other's code, found that solution is much easier.

The solution:

1. find all left boundary nodes

2. find all left leaves

3. find all right leaves

4. find all right boundary nodes.

Why do it this way? Don't aks, just rember it.

    private List<Integer> res = new ArrayList<>();
    public List<Integer> boundaryOfBinaryTree(TreeNode root) {
        if(root==null)
            return res;
        res.add(root.val);
        leftB(root.left);
        leaves(root.left);
        leaves(root.right);
        rightB(root.right);
        return res;
    }
    
    private void leftB(TreeNode root){
        if(root==null)
            return;
        if(root.left==null && root.right==null)
            return;
        res.add(root.val);
        if(root.left!=null)
            leftB(root.left);
        else
            leftB(root.right);
    }
    
    private void rightB(TreeNode root){
        if(root==null)
            return;
        if(root.left==null && root.right==null)
            return;
        
        if(root.right!=null)
            rightB(root.right);
        else
            rightB(root.left);
        res.add(root.val);
    }
    
        private void leaves(TreeNode root){
        if(root==null)
            return;
        if(root.left==null && root.right==null){
            res.add(root.val);
            return;
        }
        leaves(root.left);
        leaves(root.right);
    }

 

标签:Binary,right,return,res,Tree,Boundary,null,root,left
来源: https://www.cnblogs.com/feiflytech/p/15862527.html