[ 题目描述 ]:
[ 思路 ]:
- 二叉树的右视图:即二叉树每层最右边的节点
- BFS:使用层次遍历,每当遍历到每层最后一个节点时,记录改节点的值
- 运行如下
int* rightSideView(struct TreeNode* root, int* returnSize) {if(!root){*returnSize=0;return NULL;} struct TreeNode* nums[100];int left=0,right=0,sum=0,cur_rear=1;int* res=(int*)malloc(sizeof(int)*100);nums[right++]=root;while(left<right){if(nums[left]->left){nums[right++]=nums[left]->left;}if(nums[left]->right){nums[right++]=nums[left]->right;}if(left==cur_rear-1){res[sum++]=nums[left]->val;cur_rear=right;}left++;} *returnSize=sum;return res;
}
[ 官方题解 ]:
- 方法一:深度优先搜索:对树进行深度优先搜索,在搜索过程中,我们总是先访问右子树。那么对于每一层来说,我们在这层见到的第一个结点一定是最右边的结点。
class Solution:def rightSideView(self, root: TreeNode) -> List[int]:rightmost_value_at_depth = dict() # 深度为索引,存放节点的值max_depth = -1stack = [(root, 0)]while stack:node, depth = stack.pop()if node is not None:# 维护二叉树的最大深度max_depth = max(max_depth, depth)# 如果不存在对应深度的节点我们才插入rightmost_value_at_depth.setdefault(depth, node.val)stack.append((node.left, depth + 1))stack.append((node.right, depth + 1))return [rightmost_value_at_depth[depth] for depth in range(max_depth + 1)]
- 方法二:广度优先搜索,基本同上