数据结构-二叉树的镜像-java

1.題目

操作给定的二叉树,将其变换为源二叉树的镜像。
在这里插入图片描述
在这里插入图片描述

2.题解

先交换根节点的左右子树的位置,然后向下递归,把左右子树的根节点作为下次循环的根节点。

3.代码


public static class TreeNode {
    
    
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
        public TreeNode(int val) {
    
    
          this.val = val;
        }
      }

public static TreeNode Mirror (TreeNode pRoot) {
    
    
        TreeNode tmp;
        if(pRoot == null) {
    
    
            return pRoot;
        }
        tmp = pRoot.right;
        pRoot.right = pRoot.left;
        pRoot.left = tmp;
        Mirror(pRoot.left);
        Mirror(pRoot.right);
        return pRoot;
    }

猜你喜欢

转载自blog.csdn.net/qq_25064691/article/details/121389250