LintCode 也有相关的题目,翻转二叉树。
http://blog.youkuaiyun.com/chan15/article/details/48632357
这里有我的前、中、后序遍历的翻转二叉树非递归实现。
前序遍历(DLR,DataLeftChild RightChild):
根结点 -> 左儿子 -> 右儿子
15 6 3 2 4 7 13 9 18 17 20
LintCode的二叉树前序遍历答案:http://blog.youkuaiyun.com/chan15/article/details/48831813
递归实现:
void preorder(TreeNode *root){
if (root != NULL){
cout << root->val << endl;
preorder(root->left);
preorder(root->right);
}
}
非递归实现:
void preorder(TreeNode *root) {
TreeNode *x = root;
vector<TreeNode*> p;
while(x != NULL || p.size() != 0){
cout << root->val << endl;
if (x->right != NULL)
p.push_back(x->right);
x = x->left;
if (x == NULL && p.size() != 0){
x = p.back();
p.pop_back();
}
}
}
中序遍历(LDR,LeftChild Data RightChild):
左儿子 -> 根结点 -> 右儿子
2 3 4 6 7 9 13 15 17 18 20
LintCode的二叉树中序遍历答案:http://blog.youkuaiyun.com/chan15/article/details/48832421
PS:对二叉搜索树进行中序遍历,可以得到数组的升序排列。
中序遍历也叫投影法,直接将每个结点竖直投影下来即可得到中序遍历结果。
递归实现:
void inorder(TreeNode *root){
if (root != NULL){
inorder(root->left);
cout << root->val << endl;
inorder(root->right);
}
}
非递归实现:
void inorder(TreeNode *root) {
TreeNode *x = root;
vector<TreeNode *> p;
while(x != NULL || p.size() != 0){
while(x != NULL){
p.push_back(x);
x = x->left;
}
x = p.back();
p.pop_back();
cout << x->val << endl;
x = x->right;
}
}
后序遍历(LRD, LeftChild RightChild Data):
左儿子 -> 右儿子 -> 根结点
2 4 3 9 13 7 6 17 20 18 15
LintCode的二叉树后序遍历答案:http://blog.youkuaiyun.com/chan15/article/details/48833949
递归实现:
void postorder (TreeNode *root){
if (root != NULL){
postorder (root->left);
postorder (root->right);
cout << root->val << endl;
}
}
非递归实现:
void postorder(TreeNode *root){
int a = 1;
vector<TreeNode *> s;
while(a == 1){
while(root->left != NULL || root->right != NULL){
if(root->left != NULL){
s.push_back(root);
root = root->left;
}
else{
s.push_back(root);
root = root->right;
}
}
TreeNode *y = s.back();
while (root == y->right || y->right == NULL){
cout << root->val << endl;
s.pop_back();
if (s.size() == 0){
a = 0;
cout << y->val << endl;
break;
}
root = y;
y = s.back();
}
if (root == y->left && y->right != NULL){
cout << root->val << endl;
root = y->right;
}
}
}