Solution 1
这道题一开始我甚至没有搞清楚到底要干啥,最后才明白是“从右边”看。也就是找到每一层最右侧的一个节点。这个正好和之前的level遍历的方法相契合,因此可以直接使用BFS解决该问题。
整体思路就是,按照层次逐渐向下遍历,并保存每一层最右侧(最后一个)节点的结果。
- 时间复杂度: O ( N ) O(N) O(N),其中 N N N为输入二叉树中的节点个数,BFS线性遍历
- 空间复杂度: O ( N ) O(N) O(N),其中 N N N为输入二叉树中的节点个数,保存当前一层节点,取上界
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> ans;
if (root != nullptr) {
queue<TreeNode*> nodes;
nodes.push(root);
while(!nodes.empty()) {
int numNodes = nodes.size();
while (numNodes--) {
auto now = nodes.front();
nodes.pop();
if (now->left != nullptr) {
nodes.push(now->left);
}
if (now->right != nullptr) {
nodes.push(now->right);
}
if (numNodes == 0) {
ans.push_back(now->val);
}
}
}
}
return ans;
}
};
Solution 2
Solution 1的Python实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
ans = list()
if root is not None:
nodes = collections.deque()
nodes.append(root)
while nodes:
numNodes = len(nodes)
while numNodes > 0:
now = nodes.popleft()
if now.left is not None:
nodes.append(now.left)
if now.right is not None:
nodes.append(now.right)
numNodes -= 1
if numNodes == 0:
ans.append(now.val)
return ans