[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<— / \23<— \\ 54<—

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:7msclass 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::nums = []if root == None:return numsnodes = [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;

,平平淡淡才是真

[LeetCode] Binary Tree Right Side View

相关文章:

你感兴趣的文章:

标签云: