輸出二叉樹每一層的最右邊節點
阿新 • • 發佈:2018-11-07
輸入: [1,2,3,null,5,null,4]
輸出: [1, 3, 4]
解釋:
1 <---
/ \
2 3 <---
\ \
5 4 <---
leetcode 第199題 https://leetcode-cn.com/problems/binary-tree-right-side-view/description/
主要思想:依據佇列來實現層次遍歷,依次將最右邊的節點資料保留在陣列中,現在的問題就是怎麼判斷是最右邊的節點?
將根節點儲存在佇列中,然後取出來並在佇列中刪除該節點,這樣佇列就又為空了,
到第二層的時候也是一樣的,當佇列為空時,就把佇列為空時的前一個節點的資料保留在陣列中
/** * 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> result; if(root == nullptr) return result; queue<TreeNode *> bfs; //用佇列儲存每一層的節點 bfs.push(root); //將根節點先入佇列 while(!bfs.empty()) { int len = bfs.size(); int data = 0; for(int i = 0; i < len;i++){ TreeNode * tmp = bfs.front(); bfs.pop(); //每取出一個節點就刪除該節點,確保佇列中保留的是每一層的節點資料 data = tmp->val; if(tmp->left) bfs.push(tmp->left); if(tmp->right) bfs.push(tmp->right); } result.push_back(data);//依次將每層最右邊的節點保留下來 } return result; } };