前序遍历:根左右

//用栈来实现非递归解法
/**
* 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的更多相关文章

  1. C++版 - LeetCode 144. Binary Tree Preorder Traversal (二叉树先根序遍历,非递归)

    144. Binary Tree Preorder Traversal Difficulty: Medium Given a binary tree, return the preorder trav ...

  2. 二叉树前序、中序、后序非递归遍历 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 前序的非递归遍历:用堆来实现 如果把这个代码改成先向堆存储左节点再存储右节点,就变成了每一行从右向左打印 如果用队列替代堆,并且 ...

  3. 【LeetCode】144. Binary Tree Preorder Traversal (3 solutions)

    Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes' valu ...

  4. [LeetCode] 144. Binary Tree Preorder Traversal 二叉树的先序遍历

    Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tr ...

  5. (二叉树 递归) leetcode 144. Binary Tree Preorder Traversal

    Given a binary tree, return the preorder traversal of its nodes' values. Example: Input: [1,null,2,3 ...

  6. Java [Leetcode 144]Binary Tree Preorder Traversal

    题目描述: Given a binary tree, return the preorder traversal of its nodes' values. For example:Given bin ...

  7. 144 Binary Tree Preorder Traversal(二叉树先序遍历Medium)

    题目意思:二叉树先序遍历,结果存在vector<int>中 解题思路:1.递归(题目中说用递归做没什么意义,我也就贴贴代码吧) 2.迭代 迭代实现: class Solution { pu ...

  8. 【LeetCode】144. Binary Tree Preorder Traversal

    题目: Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binar ...

  9. 【LeetCode】144. Binary Tree Preorder Traversal 解题报告(Python&C++&Java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 迭代 日期 题目地址:https://leetc ...

随机推荐

  1. 643. Maximum Average Subarray I 最大子数组的平均值

    [抄题]: Given an array consisting of n integers, find the contiguous subarray of given length k that h ...

  2. Hyperledger Chaincode启动过程

    Chaincode 启动过程 简介 这里讲的 Chaincode 是用户链码(User Chaincode,UCC),对应用开发者来说十分重要,它提供了基于区块链分布式账本的状态处理逻辑,基于它可以开 ...

  3. Part10-C语言环境初始化-栈初始化lesson1

    1.概念解析 ARM系统使用的是满栈! ARM采用降栈!!! 栈帧 每一个进程会有一个栈,该进程中的每一个函数会分割栈的一部分,那么每一个函数使用的那部分栈就叫做栈帧.那么所有栈帧组成了整个栈. 子函 ...

  4. wireshark抓取qq数据包

    抓包接口设置成本地连接 点击start,登录qq,输入oicq进行过滤qq包 找到第一个OICQ,点击后,点击oicq-IM software 可以看到自己登录的QQ号码为765343409 本机IP ...

  5. WCF把书读薄(2)——消息交换、服务实例、会话与并发

    上一篇:WCF把书读薄(1)——终结点与服务寄宿 八.消息交换模式 WCF服务的实现是基于消息交换的,消息交换模式一共有三种:请求回复模式.单向模式与双工模式. 请求回复模式很好理解,比如int Ad ...

  6. 设计模式08: Composite 组合模式(结构型模式)

    Composite 组合模式(结构型模式) 对象容器的问题在面向对象系统中,我们常会遇到一类具有“容器”特征的对象——即他们在充当对象的同时,又是其他对象的容器. public interface I ...

  7. MySQL性能调优与架构设计——第8章 MySQL数据库Query的优化

    第8章 MySQL数据库Query的优化 前言: 在之前“影响 MySQL 应用系统性能的相关因素”一章中我们就已经分析过了Query语句对数据库性能的影响非常大,所以本章将专门针对 MySQL 的 ...

  8. [Lua快速了解一下]Lua的语法

    -注释 -- 两个减号是行注释 -块注释 --[[ 这是块注释 这是块注释 --]] -变量 Lua的数字只有double型,64bits, Lua的字符串string支持双引号或者单引号 以下例子会 ...

  9. 积分之谜——第六届蓝桥杯C语言B组(国赛)第一题

    原创 标题:积分之迷 小明开了个网上商店,卖风铃.共有3个品牌:A,B,C. 为了促销,每件商品都会返固定的积分. 小明开业第一天收到了三笔订单: 第一笔:3个A + 7个B + 1个C,共返积分:3 ...

  10. screen工具

    1.背景 系统管理员经常需要SSH 或者telent 远程登录到Linux 服务器,经常运行一些需要很长时间才能完成的任务,比如系统备份.ftp 传输等等.通常情况下我们都是为每一个这样的任务开一个远 ...