题目描述:
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]
.
解题思路:
题目中说的添加从右边看到的数并不是只添加右分支的数,当左分支的层数比右边大的时候也有可能被添加。
所以若是用递归来解题的话,我们需要用一个数来记录节点的层数,用一个数组来储存数字,只有当层数大于数组的个数(也就是添加过的数字最深层数),数字才能被添加。
然后我们做深度搜索,先从右边一条路探到黑,不行再换左边,一直递归遍历整个二叉树。以节点为空作为返回条件。
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 void view(TreeNode* root, int level, vector<int> &nums){ 13 if(!root) 14 //最底层的返回条件 15 return; 16 if(level>nums.size()) 17 //添加条件 18 nums.push_back(root->val); 19 view(root->right, level+1, nums); //右边一条路探到黑 20 view(root->left, level+1, nums); //再探左边 21 //中间节点两边搜完自动返回 22 } 23 vector<int> rightSideView(TreeNode* root) { 24 vector<int> ret; 25 view(root, 1, ret); 26 return ret; 27 } 28 };