日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

Leetcode199二叉树右视图[C++题解]:BFS+层数

發布時間:2025/4/5 c/c++ 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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+层数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。