[Illustration] Java implementation of "Sword Finger Offer": Operate a given binary tree and transform it into a mirror image of the source binary tree.

1. Title description

Operate the given binary tree and transform it into a mirror image of the source binary tree.

For example: source binary tree 
            8
           /  \
          6   10
         / \  / \
        5  7 9 11
        Mirror Binary Tree
            8
           /  \
          10   6
         / \  / \
        11 9 7  5

2. Algorithm idea

   ① First judge whether the root node is empty enough, and if the root node is empty, return null; otherwise, if there is only a root node, return the root node;

   ②  then the root node left child and right child exchange, pay attention to the exchange when the left and right child nodes to follow its exchange, and the relative position unchanged

   ③ Then the left child and the right child perform recursion

Illustration:

3. Code implementation

import java.util.*;

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

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return TreeNode类
     */
     /*
       使用递归
       1、首先判断根节点是否为空,为空的话返回空;只有根节点的话,返回根节点
       2、再判断左右节点,递归
     */
    public TreeNode Mirror (TreeNode pRoot) {
          //判断根节点是够为空
      if(pRoot == null){
         return null;
      }
        // 如果只存在根节点,返回根节点
      if(pRoot.left == null && pRoot.right == null){
        return pRoot;
      }
      // 再对子树结点进行判断
      // 定义临时结点
      TreeNode temp = pRoot.left;
      pRoot.left = pRoot.right;
      pRoot.right = temp;
      
      //递归左子树
      Mirror(pRoot.left);
      
      //递归右子树
      Mirror(pRoot.right);
      //返回根节点
      return pRoot;
    }
}


 

 

Guess you like

Origin blog.csdn.net/Sunshineoe/article/details/115012931