199. Binary Tree Right Side View

问题:

给定二叉树,求从右边观察这棵树,能看到的每层第一个元素。

Example 1:
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]

Example 2:
Input: root = [1,null,3]
Output: [1,3]

Example 3:
Input: root = []
Output: []
 
Constraints:
The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100

  199. Binary Tree Right Side View

 

 

解法:BSF,DFS

解法一:BFS

queue:每层节点

for每层节点遍历。for结束,将最后一个节点res.push_back

 

代码参考:

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

 

解法二:DFS

状态:当前层:若访问新的层(res.size<level) 将当前节点res.push_back

⚠️  注意:因为要每次访问新层的第一个节点push到res中,那么就要从右向左遍历。

对于当前节点进行,子节点递归时:

  • 先 node->right
  • 再 node->left

递归退出条件:node==null

代码参考:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     void dfs(vector<int>& res, int level, TreeNode* node) {
15         if(!node) return;
16         if(level>res.size()) res.push_back(node->val);
17         //fist right-> then left ←
18         dfs(res, level+1, node->right);
19         dfs(res, level+1, node->left);
20         return;
21     }
22     vector<int> rightSideView(TreeNode* root) {
23         vector<int> res;
24         dfs(res, 1, root);
25         return res;
26     }
27 };

 

上一篇:Severlet跳转JSP,切换div


下一篇:快速证明199的200次方大于200的199次方