前中后遍历 递归版

  /*  Recursive solution */
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) { vector<int> result;
preorderTraversal(root, result); return result;
} void preorderTraversal(TreeNode *root, vector<int>& result)
{
if(root == NULL) return;
result.push_back(root->val); preorderTraversal(root->left, result);
preorderTraversal(root->right, result);
} };
  /*  Recursive solution */
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) { vector<int> result;
inorderTraversal(root, result); return result;
} void inorderTraversal(TreeNode *root, vector<int>& result)
{
if(root == NULL) return; inorderTraversal(root->left, result);
result.push_back(root->val);
inorderTraversal(root->right, result);
} };
  /*  Recursive solution */
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) { vector<int> result;
postorderTraversal(root, result); return result;
} void postorderTraversal(TreeNode *root, vector<int>& result)
{
if(root == NULL) return; postorderTraversal(root->left, result);
result.push_back(root->val);
postorderTraversal(root->right, result);
} };

下面是迭代版本

1 preorder: 节点入栈一次, 入栈之前访问。

2 inorder:节点入栈一次,出栈之后访问。

3 postorder:节点入栈2次,第二次出战后访问。

 class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) { vector<int> result;
stack<TreeNode*> stack; TreeNode *p = root; while( NULL != p || !stack.empty())
{
while(NULL != p)
{
result.push_back(p->val); stack.push(p);
p = p->left;
} if(!stack.empty())
{
p= stack.top();
stack.pop(); p=p->right;
}
} return result;
} };
 class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) { vector<int> result;
stack<TreeNode*> stack; TreeNode *p = root; while( NULL != p || !stack.empty())
{
while(NULL != p)
{
stack.push(p);
p = p->left;
} if(!stack.empty())
{
p= stack.top();
stack.pop(); result.push_back(p->val); p=p->right;
}
} return result;
} };

后续, 用bStack标记是否是第一次访问,如果是第一次访问,再次入栈,否则直接访问,记得将P = NULL;

 class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) { vector<int> result;
stack<TreeNode*> stack;
std::stack<bool> bStack; TreeNode *p = root;
bool isFirst; while( NULL != p || !stack.empty())
{
while(NULL != p)
{
stack.push(p);
bStack.push(false);
p = p->left;
} if(!stack.empty())
{
p= stack.top();
stack.pop(); isFirst = bStack.top();
bStack.pop(); if(isFirst == )
{
stack.push(p);
bStack.push(true);
p=p->right;
}
else
{
result.push_back(p->val);
p = NULL;
} }
} return result;
} };

另外一种前序迭代实现

 class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> result;
const TreeNode *p;
stack<const TreeNode *> s;
p = root;
if (p != nullptr) s.push(p);
while (!s.empty()) {
p = s.top();
s.pop();
result.push_back(p->val);
if (p->right != nullptr) s.push(p->right);
if (p->left != nullptr) s.push(p->left);
}
return result;
}
};

Morris 遍历

morris分为3个步骤,建立link,访问最左节点,删除link,morris前序和中序遍历只要调整在那里visit节点即可,框架相同。。

可以参考:http://www.cnblogs.com/AnnieKim/archive/2013/06/15/MorrisTraversal.html

Morris算法与递归和使用栈空间遍历的思想不同,它使用二叉树中的叶节点的right指针来保存后面将要访问的节点的信息,当这个right指针使用完成之后,再将它置为NULL,但是在访问过程中有些节点会访问两次,所以与递归的空间换时间的思路不同,Morris则是使用时间换空间的思想,先来看看Morris中序遍历二叉树的算法实现:

1 Morris 中序遍历

class Solution {
public:
void morris_inorder(TreeNode* T) {
TreeNode *p, *temp;
p = T;
while(p) {
if(p->left == NULL) {
printf("%4d \n", p->val);
p = p->right;
} else {
temp = p->left;
// find the most right node of the p's left node
while(temp->right != NULL && temp->right != p) {
temp = temp->right;
}
if(temp->right == NULL) {
temp->right = p;
p = p->left;
} else {
printf("%4d \n", p->val);
temp->right = NULL;
p = p->right;
}
}
}
}
};

同时, 以 下面的二叉树为例,走一遍流程:

      4

     /            \

2               7

/    \            /   \

1      3         5     8

p指向4,  temp指向2,然后while Loop,tmp指向3, 3->right = 4, p = p->left=2; 建立链接

p指向2, tmp指向1, 然后while Loop,tmp指向1,   1->right = 2, p = p->left = 1;建立链接

p指向1, 由于p->left == NULL,visit(1), p = p ->right = 2,

p指向2, tmp指向1, 然后while Loop,tmp指向1,  visit(2), 1->right = NULL, p = p->right = 3;断开链接

p指向3, 由于p->left == NULL,visit(3), p = p ->right = 4,

p指向4, tmp指向2, 然后while Loop,tmp指向3,  visit(4), 3->right = NULL, p = p->right = 7;断开链接

p指向7, tmp指向5, 然后while Loop,tmp指向5,   5->right = 7, p = p->left = 5;建立链接

p指向5, 由于p->left == NULL,visit(5), p = p ->right = 7,

p指向7, tmp指向5, 然后while Loop,tmp指向5,  visit(7), 5->right = NULL, p = p->right = 8;断开链接

p指向8, 由于p->left == NULL,visit(3), p = p ->right = NULL,

退出循环

加上些打印信息,更好理解

class Solution {
public:
void morris_inorder(TreeNode* T) {
TreeNode *p, *temp;
p = T;
while(p) {
if(p->left == NULL) {
printf("visit %4d \n", p->val);
p = p->right;
} else {
temp = p->left;
// find the most right node of the p's left node
while(temp->right != NULL && temp->right != p) {
temp = temp->right;
}
if(temp->right == NULL) {
cout << "build link for " << temp->val <<"-->" << p->val << endl;
temp->right = p;
p = p->left;
} else {
printf("visit %4d \n", p->val);
cout << "destory link for " << temp->val <<"-->" << p->val << endl;
temp->right = NULL;
p = p->right;
}
}
}
}
}; build link for -->
build link for -->
visit
visit
destory link for -->
visit
visit
destory link for -->
build link for -->
visit
visit
destory link for -->
visit

morris 前序遍历

        void morris_preorder(TreeNode* T) {
TreeNode *p, *temp;
p = T;
while(p) {
if(p->left == NULL) {//visit the leftmost leaf node
printf("visit %4d \n", p->val);
p = p->right;
} else {
temp = p->left;
// find the most right node of the p's left node
while(temp->right != NULL && temp->right != p) {
temp = temp->right;
}
if(temp->right == NULL) {//build the link
printf("visit %4d \n", p->val);
temp->right = p;
p = p->left;
} else {//remove the link
temp->right = NULL;
p = p->right;
}
}
}
}

3 morris 后序遍历

这里的reverse 和reverse单链表意思相同,另外之所以使用链表的reverse,而没有采用辅助stack后者vector是考虑要求空间复杂度O(1)的考虑

void reverse(TreeNode *from, TreeNode *to) // reverse the tree nodes 'from' -> 'to'.
{
if (from == to)
return;
TreeNode *x = from, *y = from->right, *z;
while (true)
{
z = y->right;
y->right = x;
x = y;
y = z;
if (x == to)
break;
}
} void printReverse(TreeNode* from, TreeNode *to) // print the reversed tree nodes 'from' -> 'to'.
{
reverse(from, to); TreeNode *p = to;
while (true)
{
printf("%d ", p->val);
if (p == from)
break;
p = p->right;
} reverse(to, from);
} void postorderMorrisTraversal(TreeNode *root) {
TreeNode dump();
dump.left = root;
TreeNode *cur = &dump, *prev = NULL;
while (cur)
{
if (cur->left == NULL)
{
cur = cur->right;
}
else
{
prev = cur->left;
while (prev->right != NULL && prev->right != cur)
prev = prev->right; if (prev->right == NULL)
{
prev->right = cur;
cur = cur->left;
}
else
{
printReverse(cur->left, prev); // call print
prev->right = NULL;
cur = cur->right;
}
}
}
}

还是以上述bst为例,走一遍code:

p指向dummy,  temp指向4,然后while Loop,tmp指向8, 8->right = dummy, p = p->left=4; 建立链接

p指向4,  temp指向2,然后while Loop,tmp指向3, 3->right = 4, p = p->left=2; 建立链接

p指向2, tmp指向1, 然后while Loop,tmp指向1,   1->right = 2, p = p->left = 1;建立链接

p指向1, 由于p->left == NULL, p = p ->right = 2,

p指向2, tmp指向1, 然后while Loop,tmp指向1,  reversePrint(1,1), 1->right = NULL, p = p->right = 3;断开链接

p指向3, 由于p->left == NULL, p = p ->right = 4,

p指向4, tmp指向2, 然后while Loop,tmp指向3,  reversePrint(2,3), 3->right = NULL, p = p->right = 7;断开链接

p指向7, tmp指向5, 然后while Loop,tmp指向5,   5->right = 7, p = p->left = 5;建立链接

p指向5, 由于p->left == NULL, p = p ->right = 7,

p指向7, tmp指向5, 然后while Loop,tmp指向5,  reversePrint(5,5), 5->right = NULL, p = p->right = 8;断开链接

p指向8, 由于p->left == NULL,, p = p ->right = dummy,

p指向dummy, tmp指向4, 然后while Loop,tmp指向8,  reversePrint(4,8), 8->right = NULL, p = p->right = null;断开链接

退出循环

[LeetCode] Binary Tree Preorder/Inorder/Postorder Traversal的更多相关文章

  1. LeetCode之“树”:Binary Tree Preorder && Inorder && Postorder Traversal

    Binary Tree Preorder Traversal 题目链接 题目要求: Given a binary tree, return the preorder traversal of its ...

  2. LC 144. / 94. / 145. Binary Tree Preorder/ Inorder/ PostOrder Traversal

    题目描述 144. Binary Tree Preorder Traversal 94. Binary Tree Inorder Traversal 145. Binary Tree Postorde ...

  3. 【题解】【BT】【Leetcode】Binary Tree Preorder/Inorder/Postorder (Iterative Solution)

    [Inorder Traversal] Given a binary tree, return the inorder traversal of its nodes' values. For exam ...

  4. LeetCode: Binary Tree Preorder Traversal 解题报告

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

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

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

  6. [LeetCode] Binary Tree Preorder Traversal

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

  7. [leetcode]Binary Tree Preorder Traversal @ Python

    原题地址:http://oj.leetcode.com/problems/binary-tree-preorder-traversal/ 题意:这题用递归比较简单.应该考察的是使用非递归实现二叉树的先 ...

  8. LeetCode——Binary Tree Preorder Traversal

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

  9. LeetCode Binary Tree Preorder Traversal 先根遍历

    题意:给一棵树,求其先根遍历的结果. 思路: (1)深搜法: /** * Definition for a binary tree node. * struct TreeNode { * int va ...

随机推荐

  1. MTK 平台上如何给 camera 添加一种 preview size

    1,首先检查该项目所使用的是哪一颗sensor, 就以OV2659 为例OV2659 是一颗2M 的摄像头,Sensor 吐出的数据分辨率能达到 1600*1200,肯定是支持 1280*720 的分 ...

  2. Linux操作系统里查看所有用户

    Xwindows界面的就不说了. 1.Linux里查看所有用户 linux里,并没有像windows的net user,net localgroup这些方便的命令来管理用户. (1)在终端里.其实只需 ...

  3. AutoMapper用法(转载)

    申明 本文转载自http://www.qeefee.com/article/automapper 作者:齐飞 配置AutoMapper映射规则 AutoMapper是基于约定的,因此在实用映射之前,我 ...

  4. State Pattern -- 状态模式原理及实现(C++)

    主要参考<大话设计模式>和<设计模式:可复用面向对象软件的基础>两本书.本文介绍命令模式的实现. 问题出发点 在实际开发中,我们经常会遇到这种情况:一个对象有多种状态,在每一个 ...

  5. 【niubi-job——一个分布式的任务调度框架】----安装教程

    niubi-job是什么 niubi-job是LZ耗时三个星期,费尽心血打造的一个具备高可靠性以及水平扩展能力的分布式任务调度框架,采用quartz作为底层的任务调度管理器,zookeeper做集群的 ...

  6. 疯狂的Java算法——插入排序,归并排序以及并行归并排序

    从古至今的难题 在IT届有一道百算不厌其烦的题,俗称排序.不管是你参加BAT等高端笔试,亦或是藏匿于街头小巷的草根笔试,都会经常见到这样一道百年难得一解的问题. 今天LZ有幸与各位分享一下算法届的草根 ...

  7. git点滴的积累

    git的基本学习的网址: http://www.yiibai.com/git/git_update_operation.html 0.git首次上传代码 http://www.cnblogs.com/ ...

  8. WCF 入门(20)

    前言 Happy weekend. 第20集 通过实现IErrorHandler接口来统一处理WCF里的异常 Centralized exception handling in WCF by impl ...

  9. 第六章:javascript:字典

    字典是一种以键-值对应形式存储的数据结构,就像电话薄里的名字和电话号码一样.只要找一个电话,查找名字,名字找到后,电话号码也就找到了.这里的键值是你用来查找的东西,值就是要查的到的结果. javasc ...

  10. grunt安装

    随着node的流行,各种后台的技术应用到前端,依赖注入.自动化测试.构建等等. 本篇就介绍下如何使用Grunt进行构建. grunt安装 由于grunt依赖于nodejs,因此需要先安装nodejs. ...