前中后遍历 递归版

  /*  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. MySQL基础 - mysql命令行客户端

    在Linux系统当中,mysql作为一个客户端命令程序,在很大程度上连接数据库都是使用mysql,因此很有必要熟悉mysql命令行的使用. 这里假设数据库用户为icebug,密码为icebug_pas ...

  2. sys.stdin的三种方式

    1. for line in sys.stdin: import sys sys.stdout.write('根据两点坐标计算直线斜率k,截距b:\n') for line in sys.stdin: ...

  3. Brief introduce to Iometer

    <本人原创,纯粹为了练习英文博客的写作.转载请注明出处谢谢!非技术博客 http://shiyanch.lofter.com/ > *:first-child { margin-top: ...

  4. 进程&信号&管道实践学习记录

    程序分析 exec1.c & exect2.c & exect3.c 程序代码 (以exect1.c为例,其他两个结构类似) #include <stdio.h> #inc ...

  5. git的简介,安装以及使用

    1git的简介 Git是什么? Git是目前世界上最先进的分布式版本控制系统(没有之一). Git有什么特点?简单来说就是:高端大气上档次! 2Linus一直痛恨的CVS及SVN都是集中式的版本控制系 ...

  6. SpringMVC 中HttpMessageConverter简介和Http请求415 Unsupported Media Type的问题

    一.概述: 本文介绍且记录如何解决在SpringMVC 中遇到415 Unsupported Media Type 的问题,并且顺便介绍Spring MVC的HTTP请求信息转换器HttpMessag ...

  7. sql 2012艰难的安装

    我平台win7 64位,装了vs2012. 上午开始捣鼓到现在,先是装的sql2005,装了半天,先是32位没成功(各种协议警告ISS,asp.net一类的),后换64位冲突没成功,卸载死的心都有了, ...

  8. Java集合类: Set、List、Map、Queue使用场景梳理

    本文主要关注Java编程中涉及到的各种集合类,以及它们的使用场景 相关学习资料 http://files.cnblogs.com/LittleHann/java%E9%9B%86%E5%90%88%E ...

  9. 编写高质量代码改善C#程序的157个建议[10-12]

    前言 本文已更新至http://www.cnblogs.com/aehyok/p/3624579.html .本文主要学习记录以下内容: 建议10.创建对象时需要考虑是否实现比较器 建议11.区别对待 ...

  10. ubuntu的命令day1

    ls -i    显示所有的文件,包括隐藏的文件. 以  .  开头的文件都是隐藏文件,可以在终端用ls -i显示所有的文件.比如.ssh linux生成密钥的命令如下: 1. cd .ssh/    ...