标签:
翻转一棵二叉树
样例
1 1
/ \ / 2 3 => 3 2
/ 4 4
先翻转左子树,后翻转右子树,然后对整个树进行翻转
void swapTree(TreeNode *&root){
TreeNode *tmp = root->left;
root->left = root->right;
root->right = tmp;
}
void invertBinaryTree(TreeNode *root) {
// write your code here
if(root == NULL)
return;
invertBinaryTree(root->left);
invertBinaryTree(root->right);
swapTree(root);
}
一般非递归的实现都是利用栈来实现。遇到父节点就交换其左儿子和右儿子,如果左儿子和右儿子不为空,依次入栈
void swapTree(TreeNode *&root){
TreeNode *tmp = root->left;
root->left = root->right;
root->right = tmp;
}
void invertBinaryTree(TreeNode *root) {
// write your code here
if(root == NULL)
return;
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty())
{
TreeNode *tmp = stk.top();
stk.pop();
swapTree(tmp);
if(tmp->left)
stk.push(tmp->left);
if(tmp->right)
stk.push(tmp->right);
}
}
(175) Invert Binary Tree
http://www.lintcode.com/zh-cn/problem/invert-binary-tree/)
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/zwhlxl/article/details/47171083