Binary Tree Right Side View -- leetcode

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




基本思路:

1.广度优先搜索

广度优先搜索,在访问每层最后(最右)一个结点时,将其存入结果集中。

在leetcode上实际运行时间为8ms。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> ans;
        if (!root)
            return ans;
        queue<TreeNode *> q;
        q.push(root);
        while (!q.empty()) {
            int count = q.size();
            while (count--) {
                root = q.front();
                q.pop();
                if (!count)
                    ans.push_back(root->val);
                
                if (root->left)
                    q.push(root->left);
                if (root->right)
                    q.push(root->right);
            }
        }
        return ans;
    }
};


2. 深度优先搜索

对树做 中 右 左的 递归访问。

并在首次进入下一层次结点时,将该结点值存入结果集中。

在leetcode上实际执行时间为4ms。

class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> ans;
        dfs(root, 0, ans);
        return ans;
    }

    void dfs(TreeNode *root, int level, vector<int> &ans) {
        if (!root) return;
        if (level == ans.size())
            ans.push_back(root->val);
            
        dfs(root->right, level+1, ans);
        dfs(root->left, level+1, ans);
    }
};

深度优先搜索在执行时间要好于广度优先搜索,大约是因为队列的出、入操作都是相对耗时的操作。毕竟深度优先搜索的在运行时,栈的扩张和收缩是个非常轻量级的操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值