[LeetCode] Binary Tree Preorder/Inorder/Postorder Traversal
前中后遍历 递归版
/* 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的更多相关文章
- LeetCode之“树”:Binary Tree Preorder && Inorder && Postorder Traversal
Binary Tree Preorder Traversal 题目链接 题目要求: Given a binary tree, return the preorder traversal of its ...
- LC 144. / 94. / 145. Binary Tree Preorder/ Inorder/ PostOrder Traversal
题目描述 144. Binary Tree Preorder Traversal 94. Binary Tree Inorder Traversal 145. Binary Tree Postorde ...
- 【题解】【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 ...
- LeetCode: Binary Tree Preorder Traversal 解题报告
Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes' valu ...
- [LeetCode] Binary Tree Preorder Traversal 二叉树的先序遍历
Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tr ...
- [LeetCode] Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tr ...
- [leetcode]Binary Tree Preorder Traversal @ Python
原题地址:http://oj.leetcode.com/problems/binary-tree-preorder-traversal/ 题意:这题用递归比较简单.应该考察的是使用非递归实现二叉树的先 ...
- LeetCode——Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values. For example: Given binary t ...
- LeetCode Binary Tree Preorder Traversal 先根遍历
题意:给一棵树,求其先根遍历的结果. 思路: (1)深搜法: /** * Definition for a binary tree node. * struct TreeNode { * int va ...
随机推荐
- HTML语义化之常见模块
用合理的HTML标记以及特有的属性去格式化文档内容. 浏览器会根据标签的语义给定一个默认的样式. 判断网页标签语义是否良好的一个简单方法就是:去掉样式,看网页结构是否组织良好有序,是否仍然有很好的可读 ...
- benchmark
redis benchmark How many requests per second can I get out of Redis? Using New Relic to Understand R ...
- MATLAB-2015a安装
&1 准备工作 软件和破解文件 软件以64位为例:链接:http://pan.baidu.com/s/1qYQQPli 密码:nc1y 解压密码:www.0daydown.com 破解文件: ...
- [CareerCup] 10.6 Find Duplicate URLs 找重复的URL链接
10.6 You have 10 billion URLs. How do you detect the duplicate documents? In this case, assume that ...
- warning: LF will be replaced by CRLF
一. Git提供了一个换行符检查功能(core.safecrlf),可以在提交时检查文件是否混用了不同风格的换行符.这个功能的选项如下: false - 不做任何检查warn - 在提交时检查并警告t ...
- IOS开发之—— 各种加密的使用(MD5,base64,DES,AES)
基本的单向加密算法: BASE64 严格地说,属于编码格式,而非加密算法 MD5(Message Digest algorithm 5,信息摘要算法)SHA(Secure Hash Algorithm ...
- TPLINK GPL code 简要分析
从TPLINK官网下载了GPL code,下载后文件名是wr841nv9_en_gpl.tar.gz, 但是无论是linux还是windows下解压都提示压缩包有问题,不过还是可以解压出完整的目录的. ...
- 整理sqlserver 级联更新和删除 c#调用存储过程返回值
整理一下级联更新和删除 c#调用返回值 use master go IF exists(select 1 from sysdatabases where name='temp') BEGIN DROP ...
- 利用Ant脚本生成war包的详细步骤
使用ant脚本前的准备 1.下载一个ant安装包.如:apache-ant-1.8.4-bin.zip.解压到E盘. 2.配置环境变量.新增ANT_HOME:E:\apache-ant-1.8.4:P ...
- The web application [/codeMarket] registered the JBDC driver[.........] but failed to unregister it when the web application was stopped. To prevent
如果你报错了上面的这个严重,那么你的tomcat版本一定是在6.0.25之上的 原因:tomcat 6.025以后在sever.xml中引入了内存泄露侦测,对于垃圾回收不能处理的对像,它就会做日志. ...