Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
/**
* Definition for binary tree
* 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) {
vector<int> result;
if (!root) return result;
unordered_set<TreeNode*> visited;
stack<TreeNode*> s;
s.push(root);
while (!s.empty())
{
TreeNode *n = s.top();
// 如果左子树已经搞定,则访问本节点,
if (n->left && !visited.count(n->left)) s.push(n->left);
else
{
result.push_back(n->val);
visited.insert(n);
s.pop();
// 在访问本节点后,如果右子树存在,则压栈右子树
if (n->right) s.push(n->right);
}
}
return result;
}
};
还有一个不用哈希表记录左子树是否访问的遍历方法:
/**
* Definition for binary tree
* 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) {
vector<int> result;
TreeNode *cur = root; // 这个来记录一颗即将访问的树或子树的根节点
stack<TreeNode*> s; // 栈中保存着等待左子树访问完的节点们
while(!s.empty() || cur)
{
// 从cur开始,找到最左节点,并一路压栈
while (cur)
{
s.push(cur);
cur = cur->left;
}
// 取栈顶元素访问:(如果cur有右子树,再将右子树递归的处理)
if (!s.empty())
{
cur = s.top();
s.pop();
result.push_back(cur->val);
cur = cur->right;
}
}
return result;
}
};
针对中序遍历,还有一种是算法界大神Morris的使用O(1)额外存储空间的遍历方法,主要思想是直接使用叶子节点内不用的指针来记录下一个要访问的节点。即,在一颗子树访问完之后,势必要访问直接拥有该子树根节点r的指针,那么遍历中就让这个子树最右节点的右叶子节点临时指向r,在访问完最右的叶子节点之后,左子树全部访问完了,这时候根据最右叶子节点内保存的指针就能找到r,找到之后再把最右叶子节点的右孩子设回NULL。
来观摩一下原文:
Inorder Tree Traversal without recursion and without stack!
Using Morris Traversal, we can traverse the tree without using stack and recursion. The idea of Morris Traversal is based on Threaded Binary Tree. In this traversal, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree.
1. Initialize current as root 2. While current is not NULL If current does not have left child a) Print current’s data b) Go to the right, i.e., current = current->right Else a) Make current as right child of the rightmost node in current's left subtree b) Go to this left child, i.e., current = current->left
Although the tree is modified through the traversal, it is reverted back to its original shape after the completion. Unlike Stack based traversal, no extra space is required for this traversal.
#include<stdio.h>
#include<stdlib.h>
/* A binary tree tNode has data, pointer to left child
and a pointer to right child */
struct tNode
{
int data;
struct tNode* left;
struct tNode* right;
};
/* Function to traverse binary tree without recursion and
without stack */
void MorrisTraversal(struct tNode *root)
{
struct tNode *current,*pre;
if(root == NULL)
return;
current = root;
while(current != NULL)
{
if(current->left == NULL)
{
printf(" %d ", current->data);
current = current->right;
}
else
{
/* Find the inorder predecessor of current */
pre = current->left;
while(pre->right != NULL && pre->right != current)
pre = pre->right;
/* Make current as right child of its inorder predecessor */
if(pre->right == NULL)
{
pre->right = current;
current = current->left;
}
/* Revert the changes made in if part to restore the original
tree i.e., fix the right child of predecssor */
else
{
pre->right = NULL;
printf(" %d ",current->data);
current = current->right;
} /* End of if condition pre->right == NULL */
} /* End of if condition current->left == NULL*/
} /* End of while */
}
/* UTILITY FUNCTIONS */
/* Helper function that allocates a new tNode with the
given data and NULL left and right pointers. */
struct tNode* newtNode(int data)
{
struct tNode* tNode = (struct tNode*)
malloc(sizeof(struct tNode));
tNode->data = data;
tNode->left = NULL;
tNode->right = NULL;
return(tNode);
}
/* Driver program to test above functions*/
int main()
{
/* Constructed binary tree is
1
/ \
2 3
/ \
4 5
*/
struct tNode *root = newtNode(1);
root->left = newtNode(2);
root->right = newtNode(3);
root->left->left = newtNode(4);
root->left->right = newtNode(5);
MorrisTraversal(root);
getchar();
return 0;
}
References:
www.liacs.nl/~deutz/DS/september28.pdf
http://comsci.liu.edu/~murali/algo/Morris.htm
www.scss.tcd.ie/disciplines/software_systems/…/HughGibbonsSlides.pdf
Please write comments if you find any bug in above code/algorithm, or want to share more information about stack Morris Inorder Tree Traversal.