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);
    }

 

上一篇:随机存取流


下一篇:Java-Work9-文件输入与输出(4)