199. Binary Tree Right Side View

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

这题是求二叉树的右视图;我第一个想法就是用bfs呀,跟binary tree level order traversal那题一样的套路就行了,而bfs二叉树我已经烂熟于心了。快速地写了一下果然一次AC了。

    public List rightSideView(TreeNode root) {
        List res = new ArrayList<>();
        if (root == null) return res;
        LinkedList queue = new LinkedList<>();
        queue.add(root);
        int curNum = 1;
        int nextNum = 0 ; 
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            curNum -- ; 
            
            if (node.left!=null){
                queue.offer(node.left);
                nextNum ++ ; 
            }

            if (node.right!=null){
                queue.offer(node.right);
                nextNum ++ ;
            }
            
            if (curNum==0){
                res.add(node.val);
                curNum = nextNum ; 
                nextNum = 0 ;
            }
        }
        return res ; 
    }

晚上回来看看dfs之类的其他解法吧。上班去了。

下班回来了..

现在是晚上10:40分了,感觉也没干什么突然间就这么晚了。。六点半去健身,健身完了磨蹭了一下去吃了个饭九点才回家,回来做了一组腹肌训练然后洗澡,就十点多了。。有点烦啊。以后我决定中午去健身了,然后晚上早点回。

回到正题,刚才用dfs写了一下,还是模仿的binary tree level order traversal的dfs写法,dfs函数像这样:

    private void dfs(TreeNode root, int level, ArrayList> list) {
        if (root == null) return;
        if (level >= list.size()) {
            list.add(new ArrayList());
        }
        list.get(level).add(root.val);
        dfs(root.left, level + 1, list);
        dfs(root.right, level + 1, list);
    }

这么做需要O(n)的Space,因为需要把每一行的元素都存起来然后读每个sublist的最后一个元素。

然后我去看了leetcode高票答案,果然有奇淫巧技。。如下:

public class Solution {
    public List rightSideView(TreeNode root) {
        List result = new ArrayList();
        rightView(root, result, 0);
        return result;
    }
    
    public void rightView(TreeNode curr, List result, int currDepth){
        if(curr == null){
            return;
        }
        if(currDepth == result.size()){
            result.add(curr.val);
        }
        
        rightView(curr.right, result, currDepth + 1);
        rightView(curr.left, result, currDepth + 1);
        
    }
}

乍一看有点难以理解,跟dfs几乎一样,但是不同的是它每次先遍历右子树,然后遍历左子树,然后把每层traverse到的第一个元素的val保存起来。空间复杂度O(logN)。

同理,左视图的话,就把这左右child 递归的顺序换一下位置就好了。

我就在想,既然如此是不是不需要遍历左子树了。。当然不行了,因为遇到只有left child的node的时候无法进入下一层呀。比如下面的case就不行。

Input:
[1,2]
Output:
[1]
Expected:
[1,2]

dfs(递归)跟tree结合真是非常完美,两者都有层的概念。

那么,今天就到这里了。晚安。

你可能感兴趣的:(199. Binary Tree Right Side View)