剑指offer二叉树的镜像

递归就好,比如root节点,交换左右子树,然后对于左右子树,再各自交换对应的左右子树

不过这些代码都是inplace的不要返回状态

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回镜像树的根节点
    def Mirror(self, root):
        # write code here
        if root == None:
            return
        root.left,root.right = root.right,root.left
        if(root.left):
            self.Mirror(root.left)
        if(root.right):
            self.Mirror(root.right)

java代码

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public void Mirror(TreeNode root) {
        TreeNode tmp = new TreeNode(0);
        if(root == null){
            return;
        }

        tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        if(root.left!=null){this.Mirror(root.left);}
        if(root.right!=null){this.Mirror(root.right);}
    }
}

猜你喜欢

转载自blog.csdn.net/qq_17641711/article/details/82965382