LeetCode199 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.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

题源:here;完整实现:here

思路:

我们利用分层遍历的思想,将每一层的最后一个数放到结果中,这里请注意对如何更新最后一个数的处理:

class Solution {
public:
	vector<int> rightSideView(TreeNode* root) {
		queue<TreeNode*> d;
		vector<int> res;
		TreeNode *last = root;
		d.push(root);
		while (root) {
			if (root->left) d.push(root->left);
			if (root->right) d.push(root->right);
			if (root == last) { res.push_back(root->val); last = d.back(); }
			d.pop();
			if(!d.empty()) root = d.front();
			else root = NULL;
		}
		return res;
	}
};

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/88574977