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

这道题从一棵二叉树的右侧观察,,返回观察到的结点的值的集合。

很容易想到,利用层次遍历,每一层的最后一个结点就是观察到的结点之一。

/** * Definition for binary tree * 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> ans;if (!root)return ans;queue<TreeNode*> q;q.push(root);int count = 1;int num = 0;while (!q.empty()){root = q.front();q.pop();count–;if (root->left){q.push(root->left);num++;}if (root->right){q.push(root->right);num++;}if (count == 0){ans.push_back(root->val);count = num;num = 0;}}return ans;}};

对人性的弱点有清醒的认识,

[LeetCode]Binary Tree Right Side View

相关文章:

你感兴趣的文章:

标签云: