前中后遍历 递归版

  /*  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. Linux常用指令---$PATH (环境变量)

    实例一:设置临时环境变量 在linux服务器上设置临时环境变量,当退出shell环境时,自动销毁 export JAVA_HOME=/usr/java/jdk1.6.0_32 export class ...

  2. 20135220谈愈敏Blog6_进程的描述和创建

    进程的描述和创建 谈愈敏 原创作品转载请注明出处 <Linux内核分析>MOOC课程 http://mooc.study.163.com/course/USTC-1000029000 进程 ...

  3. SQL脚本循环修改数据库字段类型

    数据库在设计的时候也许考虑不全面,导致某些字段类型不太准确.比如设计的时候是varchar(1024),但是实际使用的时候却发现太小了,装不下,于是需要修改字段类型为ntext什么的. 我最近就遇到了 ...

  4. 程序员"青春饭"问题之我见

      程序员"青春饭"问题之我见 声明:转载请注明出处.http://www.cnblogs.com/hzg1981/ 1. 问题描述 问题1: 什么是程序员? 在本文中程序员的定义 ...

  5. Bootstrap系列 -- 29. 按钮组

    单个按钮在Web页面中的运用有时候并不能满足我们的业务需求,常常会看到将多个按钮组合在一起使用,比如富文本编辑器里的一组小图标按钮等 按钮组和下拉菜单组件一样,需要依赖于button.js插件才能正常 ...

  6. Jquery实现异步上传图片

    利用jQuery的ajax函数就可以实现异步上传图片了.一开始我是想在处理程序中,直接用context.Request.Files来获取页面中的input file,但是不知道为什么一次获取不了.网上 ...

  7. RESTful WebService入门(转)

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://lavasoft.blog.51cto.com/62575/229206 REST ...

  8. “耐撕”团队 2016.3.25 站立会议

    成员: Z 郑蕊 * 组长 (博客:http://www.cnblogs.com/zhengrui0452/), P 濮成林(博客:http://www.cnblogs.com/charliePU/) ...

  9. usefull-url

    http://www.johnlewis.com/ http://codepen.io/francoislesenne/pen/aIuko http://www.rand.org/site_info/ ...

  10. 《疯狂Java:突破程序员基本功的16课》读书笔记-第二章 对象与内存控制

    Java内存管理分为两个方面:内存分配和内存回收.这里的内存分配特指创建Java对象时JVM为该对象在堆内存中所分配的内存空间.内存回收指的是当该Java对象失去引用,变成垃圾时,JVM的垃圾回收机制 ...