栈和递归的关系 144:Binary Tree Preorder Traversal
前序遍历:根左右
//用栈来实现非递归解法
/**
* 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> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root == NULL)
return res;
stack<TreeNode*> stack;
stack.push(root); while(!stack.empty()){
TreeNode* c = stack.top();
stack.pop();
res.push_back(c->val);
if(c->right)
stack.push(c->right);
if(c->left)
stack.push(c->left);
}
return res;
}
};
//递归解法,注意res是全局的,要放在遍历函数外面
/**
* 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> res;
vector<int> preorderTraversal(TreeNode* root) { if(root){
res.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
return res;
}
};
中序遍历:左根右
/**
* 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> inorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> res;
if(root == NULL) return res; //若根节点为空则返回空
TreeNode* p = root;
while(p || !st.empty()){
while(p){
//先将根节点入栈,再将它所有的左节点入栈
st.push(p);
p = p->left;
} p = st.top();
st.pop();
res.push_back(p->val);
p = p->right;
}
return res;
}
};
后序遍历:左右根
可以使其遍历顺序为根左右,然后逆序插入vector中,即每次在vector的头部插入结点值。在压入栈时先压入右结点再压入左结点则在出栈时就是先左后右了。
//解法一
/**
* 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> postorderTraversal(TreeNode* root) {
if(!root) return {};
vector<int> res;
stack<TreeNode*> s{{root}};
while(!s.empty()){
TreeNode* t = s.top();
s.pop();
res.insert(res.begin(), t->val);
if(t->left) s.push(t->left);
if(t->right) s.push(t->right);
}
return res;
}
};
解法二:关键是判断当前这个结点:
1)它如果有左右结点是否已经入栈,若没有入栈则先将它的右结点入栈,再左结点入栈;如果它的左右结点已经入栈,则这个结点就可以直接加入容器vector里了。
2)如果它是叶子结点(没有左右结点),则直接加入vector中。
/**
* 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> postorderTraversal(TreeNode* root) {
if(!root) return {};
vector<int> res;
stack<TreeNode*> s{{root}};
TreeNode* head = root; //head初始化
while(!s.empty()){
TreeNode* t = s.top();
if((!t->left && !t->right) || t->left==head || t->right==head){
//当t为叶子结点 或t的左结点或右结点为head,即已经入栈了
res.push_back(t->val);
s.pop();
head = t;
}
else{
if(t->right) s.push(t->right);
if(t->left) s.push(t->left);
}
}
return res;
}
};
leetcode已经分别定义了类NestedInteger中的三个函数:
1)isInteger():若当前这个NestedInteger是单个整数返回true;
2)getInteger():返回当前这个单个的整数;
3)getList():返回当前这个列表。
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/
class NestedIterator {
public:
stack<NestedInteger> s; NestedIterator(vector<NestedInteger> &nestedList) {
for(int i=nestedList.size()-; i>=; i--)
//倒序插入 是为了弹出时是正序的
s.push(nestedList[i]);
} int next() {
//返回下一项的值
NestedInteger t = s.top();
s.pop();
return t.getInteger(); //获取对应整数 } bool hasNext() {
//若下一项有值,返回true
while(!s.empty()){
NestedInteger t = s.top();
if(t.isInteger())
return true; //若下一个数是单个整数,返回true
s.pop();
//若下一个数是一个列表,使用getList()得到列表的每个整数倒序插入到栈中
for(int i=t.getList().size()-; i>=; i--)
s.push(t.getList()[i]);
}
return false;
}
}; /**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i(nestedList);
* while (i.hasNext()) cout << i.next();
*/
栈和递归的关系 144:Binary Tree Preorder Traversal的更多相关文章
- C++版 - LeetCode 144. Binary Tree Preorder Traversal (二叉树先根序遍历,非递归)
144. Binary Tree Preorder Traversal Difficulty: Medium Given a binary tree, return the preorder trav ...
- 二叉树前序、中序、后序非递归遍历 144. Binary Tree Preorder Traversal 、 94. Binary Tree Inorder Traversal 、145. Binary Tree Postorder Traversal 、173. Binary Search Tree Iterator
144. Binary Tree Preorder Traversal 前序的非递归遍历:用堆来实现 如果把这个代码改成先向堆存储左节点再存储右节点,就变成了每一行从右向左打印 如果用队列替代堆,并且 ...
- 【LeetCode】144. Binary Tree Preorder Traversal (3 solutions)
Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes' valu ...
- [LeetCode] 144. Binary Tree Preorder Traversal 二叉树的先序遍历
Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tr ...
- (二叉树 递归) leetcode 144. Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values. Example: Input: [1,null,2,3 ...
- Java [Leetcode 144]Binary Tree Preorder Traversal
题目描述: Given a binary tree, return the preorder traversal of its nodes' values. For example:Given bin ...
- 144 Binary Tree Preorder Traversal(二叉树先序遍历Medium)
题目意思:二叉树先序遍历,结果存在vector<int>中 解题思路:1.递归(题目中说用递归做没什么意义,我也就贴贴代码吧) 2.迭代 迭代实现: class Solution { pu ...
- 【LeetCode】144. Binary Tree Preorder Traversal
题目: Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binar ...
- 【LeetCode】144. Binary Tree Preorder Traversal 解题报告(Python&C++&Java)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 迭代 日期 题目地址:https://leetc ...
随机推荐
- zend studio在线安装svn的插件
这个,其实真的很简单 ,但是让我纠结了很久. 安装步骤: 1.确保电脑能够上网: 2.打开zend studio,然后选择help->welcome会弹出一个欢迎页面; 3.等待几秒后可以看到右 ...
- 819. Most Common Word 统计高频词(暂未被禁止)
[抄题]: Given a paragraph and a list of banned words, return the most frequent word that is not in the ...
- 当集合里存储的是URL时的一些问题总结
先看道题吧: package com.lk.C; import java.net.MalformedURLException; import java.net.URL; import java.uti ...
- 安装CentOS 6网络配置问题
安装CentOS 6网络配置问题 今天决定把家中的CentOS从5升级至6.但安装完CentOS 6.2之后发现eth0没有像往常一样通过DHCP自动获取IP.打开“/etc/sysconfig/ne ...
- 解决selenium与firefox版本不兼容问题
Python环境下类比 个人使用 32位环境 Python 2.7.12 Selenium 2.53.6 Firefox 47.01 安装selenium可用pip选择对应版本,参考另一教程. 因为在 ...
- 第十二课 Actionlib(1)
一\Actionlib概念 在ROS系统中,有时需发送请求给某个节点完成相应的任务,同时获得一个一个响应,这种情况下可以通过ROS服务来 完成;然而,在某些情况下,服务需要很长时间才能执行完,如让机器 ...
- Python基础入门-For循环
For循环的功能比较强大,他可以帮助我们实现很多重复性的工作.而且for循环能迭代不同的数据结构.他的应用也十分的广泛,作为初学者,我们需要对循环的概念多加理解和练习.接下来我们就来学习for循环的一 ...
- svn ank问题
subvesion detected a working copy that need upgrade in 可以先在文件夹下cleapup,然后打开解决方案,在解决方案的右键选择upgrade wo ...
- Linq学习<一>
lambda查询语法: var result =arrarylist.where(n=>n.contains("l")) 简化的委托方法实例 linq查询结构: var ...
- 《Wonderland: A Novel Abstraction-Based Out-Of-Core Graph Processing System》章明星
在2018年3月28日于美国弗吉尼亚州威廉斯堡结束的ACM ASPLOS 2018会议上,计算机系高性能所师生发表了两篇长文.一篇是我系博士生章明星为第一作者,导师武永卫为通讯作者的“Wonderla ...