Binary Tree Right Side View -- leetcode
2015-07-07 07:31
393 查看
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,
You should return
基本思路:
1.广度优先搜索
广度优先搜索,在访问每层最后(最右)一个结点时,将其存入结果集中。
在leetcode上实际运行时间为8ms。
2. 深度优先搜索
对树做 中 右 左的 递归访问。
并在首次进入下一层次结点时,将该结点值存入结果集中。
在leetcode上实际执行时间为4ms。
深度优先搜索在执行时间要好于广度优先搜索,大约是因为队列的出、入操作都是相对耗时的操作。毕竟深度优先搜索的在运行时,栈的扩张和收缩是个非常轻量级的操作。
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); } };
深度优先搜索在执行时间要好于广度优先搜索,大约是因为队列的出、入操作都是相对耗时的操作。毕竟深度优先搜索的在运行时,栈的扩张和收缩是个非常轻量级的操作。
相关文章推荐
- Mysql子查询,连接,多表更新
- 寒冰王座(完全背包+多解)
- [Objective-C] @property是不能被“预处理”的,而是直接编译成汇编指令
- yum 遇到 python运行问题
- Adb connection Error:远程主机强迫关闭了一个现有的连接 解决方法
- 线性代数MIT-1、方程组的几何解释
- 黑马程序员---OC基础---常见错误汇总
- Linux 命令行中的幽默
- OSChina 周二乱弹 —— 静静看你们互喷
- 2015070703 - 7.7
- HTML Form表单详解
- cast 用法
- 2015070702 - EffactiveJava笔记 - 第14条 共有类使用访问方法而非共有属性
- FPGA内部RAM的初始化
- ‘svn’不是内部或外部命令,也不是可运行的程序
- 汽车安全气囊是如何工作的,我们应当注意那些?
- Win 10来袭,人工智能女将打头阵
- 2015070701 - EffactiveJava笔记 - 第13条 使类和成员的可访问性最小(3)
- leetcode 230: Kth Smallest Element in a BST
- java学习篇-------字符串和文本I/O