题目链接: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.

For example:

Given the following binary tree,

   1            <--- 
 /   \ 
2     3         <--- 
 \     \ 
  5     4       <--- 

You should return [1, 3, 4].

这道题的要求是找出从二叉树右侧所看到的节点(从上到下的顺序),也就是从上到下找出每层的最右边的节点。

Binary Tree Level Order TraversalBinary Tree Zigzag Level Order TraversalBinary Tree Level Order Traversal II都是类似的题目,同样采用广度优先搜索,引入变量n记录每层的节点数量,然后记录每层的最右边节点。

时间复杂度:O(n)

空间复杂度:O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution
{
public:
    vector<int> rightSideView(TreeNode *root)
    {
        vector<int> res;
        
        if(root == NULL)
            return res;
        
        queue<TreeNode *> q;
        q.push(root);
        while(!q.empty())
            for(int i = 0, n = q.size(); i < n; ++ i)
            {
                TreeNode *p = q.front();
                q.pop();
                if(p -> left != NULL)
                    q.push(p -> left);
                if(p -> right != NULL)
                    q.push(p -> right);
                if(i == n - 1)
                    res.push_back(p -> val);
            }
        
        return res;
    }
};