[LeetCode 199] Binary Tree Right Side View (遞迴的層數)
阿新 • • 發佈:2019-01-02
題目內容
199 Binary Tree Right Side View
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <—
/ \
2 3 <—
\ \
5 4 <—
You should return [1, 3, 4].
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
題目原文
題目簡述
從上到下寫出二叉樹每層最右側節點對應的數值
題目分析
按層次遞迴,並將層數作為遞迴變數使每層只記錄一個數值,從右至左遍歷則使每層右邊節點最先遍歷,該節點數值即可在本層唯一記錄。
程式碼示例
/**
* 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:
void recursion(vector<int> &res,TreeNode *root,int level)
{
if(root==NULL) return;
if(res.size()<level) res.push_back(root->val);
recursion(res,root->right,level+1);
recursion(res,root->left,level+1);
}
vector <int> rightSideView(TreeNode *root)
{
vector<int> res;
recursion(res,root,1);
return res;
}
};