2015.4.17 06:04
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,
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].
You should return [1, 3, 4]
.
Solution:
Recursion can provide you with a short solution. So make it simple.
Accepted code:
1 // 1AC, easy with recursive 2 /** 3 * Definition for binary tree 4 * struct TreeNode { 5 * int val; 6 * TreeNode *left; 7 * TreeNode *right; 8 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 vector<int> rightSideView(TreeNode *root) { 14 vector<int> res; 15 if (root == nullptr) { 16 return res; 17 } 18 19 dfs(root, 1, res); 20 return res; 21 } 22 private: 23 void dfs(TreeNode *ptr, int dep, vector<int> &res) { 24 if (dep > res.size()) { 25 res.push_back(ptr->val); 26 } 27 28 if (ptr->right != nullptr) { 29 dfs(ptr->right, dep + 1, res); 30 } 31 if (ptr->left != nullptr) { 32 dfs(ptr->left, dep + 1, res); 33 } 34 } 35 };