27、 二叉树的镜像(mirrorTree)

27、 二叉树的镜像(mirrorTree)

1. python

class Solution:
    def mirrorTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return
        self.mirrorTree(root.left)
        self.mirrorTree(root.right)
        root.left,root.right = root.right,root.left 
        return root

2. Java

class Solution {
    
    
    public TreeNode mirrorTree(TreeNode root) {
    
    
        if(root==null){
    
    
            return null;
        }
        this.mirrorTree(root.left);
        this.mirrorTree(root.right);
        TreeNode tmp=root.left;
        root.left=root.right;
        root.right=tmp;
        return root;
    }
}

3. C++

class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        if(root==NULL){
            return NULL;
        }
        mirrorTree(root->left);
        mirrorTree(root->right);
        swap(root->left,root->right);
        return root;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_44294385/article/details/112228190
今日推荐