LeetCode - 解题笔记 - 199 - Binary Tree Right Side View

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值