Leetcode199二叉树右视图[C++题解]:BFS+层数
生活随笔
收集整理的這篇文章主要介紹了
Leetcode199二叉树右视图[C++题解]:BFS+层数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 題目
- 思路
- 提交代碼(ac代碼)
- 測試代碼
題目
Leetcode199二叉樹右視圖
給定一棵二叉樹,想象自己站在它的右側,按照從頂部到底部的順序,返回從右側所能看到的節點值。
示例:
輸入: [1,2,5,4,5,6] 輸出: [1, 5, 6] 解釋:1 <---/ \ 2 5 <--- / \ \ 4 5 6 <---思路
層次遍歷二叉樹,也就是廣度優先搜索BFS
這里需要做的是如何把每一層最后一個元素進行標記。
我們把節點和它所在的層數組在一起同時入隊列Q。
queue<pair<TreeNode*,int> > Q;
然后可以求解層數的問題
提交代碼(ac代碼)
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/ class Solution { public:vector<int> rightSideView(TreeNode* root){vector<int> view;//save the resultqueue<pair<TreeNode*,int> > Q;if(root)Q.push(make_pair(root,0));//root and its level 0while(!Q.empty()){TreeNode* node=Q.front().first;//current nodeint depth=Q.front().second;//level of the nodeQ.pop();if(view.size()==depth)//每行第一個 view.push_back(node->val);elseview[depth]=node->val;//每行只存一個,不斷更新 if(node->left)Q.push(make_pair(node->left,depth+1));if(node->right)Q.push(make_pair(node->right,depth+1)); }return view;} };測試代碼
#include<iostream>#include<vector>#include<queue>using namespace std;struct TreeNode{int val;TreeNode* left;TreeNode* right;TreeNode(int x):val(x),left(NULL),right(NULL){} };vector<int> rightSideView(TreeNode* root){vector<int> view;//save the resultqueue<pair<TreeNode*,int> > Q;if(root)Q.push(make_pair(root,0));//root and its level 0while(!Q.empty()){TreeNode* node=Q.front().first;//current nodeint depth=Q.front().second;//level of the nodeQ.pop();if(view.size()==depth)//每行第一個 view.push_back(node->val);elseview[depth]=node->val;//每行只存一個,不斷更新 if(node->left)Q.push(make_pair(node->left,depth+1));if(node->right)Q.push(make_pair(node->right,depth+1)); }return view;}int main(){TreeNode a(1);TreeNode b(2);TreeNode c(5);TreeNode d(3);TreeNode e(4);TreeNode f(6);a.left=&b;a.right=&c;c.right=&f;b.left=&d;b.right=&e;vector<int> test;test=rightSideView(&a);for(size_t i=0;i<test.size();++i)cout<<test[i]<<"";return 0;}測試結果
總結
以上是生活随笔為你收集整理的Leetcode199二叉树右视图[C++题解]:BFS+层数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端css学习
- 下一篇: AcWing 845. 八数码(3阶数字