Leetcode: Binary Tree Right Side View
I. Question
Let's give you a binary tree. Assume that a few are standing behind the tree, then you can only see the rightmost node.
For example:
1 <---
/\
2 3 <---
\\
5 4 <---
The return value is [1, 3, 4].
Ii. Analysis
We usually use DFS or BFS for tree traversal. This topic is actually traversal. However, we only need to record the rightmost node of each row. My first thought was to access only the right node each time. But when I thought about it carefully, not all of them were in this situation. For example, the rightmost node may be in the left half. I immediately dismissed this idea and thought that we had to traverse all the nodes in any case. However, we had to traverse the nodes in a forward order in disguised form, that is, the order of the current node-Right node-left node, they are put into the queue every time, but we only need to record the first node, and all others are released.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector
rightSideView(TreeNode *root) { vector
res; if(root == NULL) return res; queue
nQueue; TreeNode *node = root; nQueue.push(node); while(!nQueue.empty()){ int size = nQueue.size(); for(int i = 0; i < size; i++){ node = nQueue.front(); nQueue.pop(); if(i == 0) res.push_back(node->val); if(node->right) nQueue.push(node->right); if(node->left) nQueue.push(node->left); } } return res; }};