Invert Binary Tree
nvert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
这道题也称为求二叉树的镜像
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return root;
TreeNode *newLeft = invertTree(root->right);
TreeNode *newRight = invertTree(root->left);
root->left = newLeft;
root->right = newRight;
return root;
}
/**
* 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* r) {
if(r == NULL) return r;
if(r->left == NULL && r->right == NULL) return r;
swapTreeChild(r);
if(r->left) invertTree(r->left);
if(r->right) invertTree(r->right);
return r;
}
private:
void swapTreeChild(TreeNode *p){
TreeNode *temp = p->left;
p->left = p->right;
p->right = temp;
}
};
迭代的版本
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return root;
if(root->left == NULL && root->right == NULL) return root;
stack<TreeNode *>st;
st.push(root);
while(!st.empty()){
TreeNode *temp = st.top();
st.pop();
if(temp->left) st.push(temp->left);
if(temp->right) st.push(temp->right);
swapTreeChild(temp);
}
return root;
}
private:
void swapTreeChild(TreeNode *p){
TreeNode *temp = p->left;
p->left = p->right;
p->right = temp;
}
};