[LeetCode] 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].

实现代码1

```/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ // Runtime:7ms class Solution { public: vector<int> rightSideView(TreeNode *root) { vector<int> nums; queue<TreeNode*> nodes; if (root != NULL) { nodes.push(root); } TreeNode *cur; while (!nodes.empty()) { int size = nodes.size(); for (int i = 0; i < size; i++) { cur = nodes.front(); nodes.pop(); if (cur->left != NULL) { nodes.push(cur->left); } if (cur->right != NULL) { nodes.push(cur->right); } } nums.push_back(cur->val); } ```

``` return nums; } };```

实现代码2

```# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Runtime:74ms class Solution: # @param root, a tree node # @return a list of integers def rightSideView(self, root): nums = [] if root == None: return nums nodes = [root] while nodes: size = len(nodes) for i in range(size): cur = nodes.pop(0) if cur.left != None: nodes.append(cur.left) if cur.right != None: nodes.append(cur.right) nums.append(cur.val) ```

``` return nums; ```

1. 本站所有资源来源于用户上传和网络，如有侵权请邮件联系站长！
2. 分享目的仅供大家学习和交流，您必须在下载后24小时内删除！
3. 不得使用于非法商业用途，不得违反国家法律。否则后果自负！
4. 本站提供的源码、模板、插件等等其他资源，都不包含技术服务请大家谅解！
5. 如有链接无法下载、失效或广告，请联系管理员处理！
6. 本站资源售价只是赞助，收取费用仅维持本站的日常运营所需！
7. 如遇到加密压缩包，请使用WINRAR解压,如遇到无法解压的请联系管理员！