思路:递归解决,在返回root前保证该点的两个孩子已经互换了。注意可能给一个Null。
C++
/**
* 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) return ;//重要在这而已
if(root->left) invertTree(root->left);
if(root->right) invertTree(root->right);
TreeNode* tmp=root->right;
root->right=root->left;
root->left=tmp;
return root;
}
};
AC代码
python3
递归
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root!=None:
root.left, root.right= self.invertTree(root.right), self.invertTree(root.left)
return root
AC代码
迭代
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
stack=[root]
while stack!=[]:
back=stack.pop()
if back!=None:
back.left, back.right= back.right, back.left
stack.extend([back.left,back.right])#也可以写成stack+=back.left,back.right return root
AC代码