[leetcode] 199. Binary Tree Right Side View
2017-03-17 09:17
106 查看
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,
You should return [1, 3, 4]
我的代码
可以广搜也可以深搜:深搜代码:
/** * 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> rlt; dfs(root, 1, rlt); return rlt; } private: void dfs(TreeNode* root, int step, vector<int>& vec) { if (!root) return; if (vec.size()<step) vec.push_back(root->val); dfs(root->right, step+1, vec); dfs(root->left, step+1, vec); } };
广搜代码:
*/ class Solution { public: vector<int> rightSideView(TreeNode* root) { queue<TreeNode*> q; vector<int> rlt; if (root) { q.push(root); while(!q.empty()) { rlt.push_back(q.front()->val); int _size=q.size(); while(_size) { TreeNode* tmp=q.front(); q.pop(); if (tmp->right) q.push(tmp->right); if (tmp->left) q.push(tmp->left); _size--; } } } return rlt; } };
相关文章推荐
- LeetCode: Combination Sum II
- LeetCode-Valid Number
- leetcode - Reverse Words in a String
- LeetCode题解——Reverse Integer
- LeetCode 120. Triangle
- [leetcode]Count and Say
- LeetCode-Word Break
- LeetCode 192:Reverse Bits
- LeetCode: Climbing Stairs
- leetcode 225 Implement Stack using Queues
- Leetcode 187 Repeated DNA Sequences 重复出现的DNA序列
- leetcode-31 Next Permutation 数字排列组合找到下一个更大值
- leetcode -- Spiral Matrix -- 思路简单,但很麻烦
- LeetCode :232. Implement Queue using Stacks(剑指offer面试题)
- 【LeetCode】50. Pow(x, n)解法及注释
- leetcode(11), Number of 1 Bits(python)
- 【leetcode】102. Binary Tree Level Order Traversal
- leetcode:sort:Maximum Gap(164)
- leetCode No.199 Binary Tree Right Side View
- [leetcode][401]. Binary Watch