一.解法
https://leetcode-cn.com/problems/invert-binary-tree/
要点:递归,树
Python,C++,Java都用了二叉树递归的方法,如果当前节点是空就返回空,当前节点有值,就交换左孩子和右孩子后返回当前节点。
二.Python实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
temp=TreeNode(0)
if root==None:
return None
else:
temp=root.left
root.left=root.right
root.right=temp
if root.left!=None:
self.invertTree(root.left)
if root.right!=None:
self.invertTree(root.right)
return root
三.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) {
TreeNode *temp;
if(!root) return NULL;
if(root){
temp=root->left;
root->left=root->right;
root->right=temp;}
if(root->left)
invertTree(root->left);
if(root->right)
invertTree(root->right);
return root;
}
};
四.java实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
TreeNode temp;
if(root==null) return null;
else{
temp=root.left;
root.left=root.right;
root.right=temp;
if(root.left!=null) invertTree(root.left);
if(root.right!=null) invertTree(root.right);
}
return root;
}
}