问题描述
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
思路分析
反转一棵二叉树,将二叉树所有的左子树和右子树互换。难倒了Max Howell大神的Google面试题。
思路一:递归每一层树,将左右子树翻转,直到叶子结点,leaf->left or leaf->right为null时,递归停止。
思路二:从root开始遍历这棵树,并将每一个结点储存在栈中。每次出栈一个元素,在结点不为NULL的情况下,互换左右子树。
代码
递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root){
invertTree(root->left);
invertTree(root->right);
swap(root->left, root->right);
}
return root;
}
};
时间复杂度:
O(n)
空间复杂度:
O(1)
栈迭代
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
stack<TreeNode*> stk;
TreeNode* pointer;
stk.push(root);
while (!stk.empty()){
pointer = stk.top();
stk.pop();
if(pointer != NULL){
stk.push(pointer->left);
stk.push(pointer->right);
swap(pointer->left, pointer->right);
}
}
return root;
}
};
时间复杂度:
O(n)
空间复杂度:
O(n)
反思
翻转树的关键在于镜面对称,所有结点都要翻转,掌握这个关键点,可以比较轻松的解题。