LeetCode----Add and Search Word - Data structure design

本文介绍了一种解决二叉树右视图问题的方法,通过层次遍历获取每层最右侧节点的值。提供了两种不同的实现方案,一种是利用双指针技巧,另一种则是通过队列实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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            <---
 /   \
2     3         <---
 \     \
  5     4       <---

You should return [1, 3, 4].


分析:

这题比较有意思,从右边查看二叉树。

这题可以采用层次遍历的方式,每次获取当前层最后遍历的元素保存起来。

我这里用的是编程之美里提到的双指针法,大概的思路是:使用list存储所有遍历到的元素,前指针每次记录当前层开始位置的元素的位置,后指针每次记录当前层最后一个元素的位置,使用另一个list存储后指针每次位置的元素的值,即为所要的结果。遍历时,前指针依次遍历它所指的位置的元素直到到达后指针所指向的元素,同时将遍历时经过的元素添加到list中。


代码:

class Solution(object):
    def rightSideView(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        res = []
        vis = []
        p = root
        if p:
            vis.append(p)
            front, end = 0, 1
        else:
            return res
        while front < end:
            res.append(vis[-1].val)
            while front < end:
                cur = vis[front]
                if cur.left:
                    vis.append(cur.left)
                if cur.right:
                    vis.append(cur.right)
                front += 1
            end = len(vis)
        return res


从Discuss中看到的代码:

vector<int> rightSideView(TreeNode* root) {
    vector<int> V;
    queue<TreeNode*> Q;
    if (root!=NULL) Q.push(root);
    while (!Q.empty()) {
        int k = Q.size();
        for (int i=0; i<k; i++) {
            TreeNode* rt = Q.front();
            if (i==0) V.push_back(rt->val);
            if (rt->right)Q.push(rt->right);
            if (rt->left) Q.push(rt->left);
            Q.pop();
        }
    }
    return V;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值