Binary Tree Mirror-Java

Binary Tree Mirror-Java

Title description

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

比如:    源二叉树 
            8
           /  \
          6   10
         / \  / \
        5  7 9 11
        镜像二叉树
            8
           /  \
          10   6
         / \  / \
        11 9 7  5

Example 1

enter

{8,6,10,5,7,9,11}

return value

{8,10,6,11,9,7,5}

After reading it, I feel very good, because I just finished the merging of the ordered linked list, and I think it's almost the same. But in fact it is not the same. First of all, each node has children, which is different from merging a linked list. Recursion is used here.

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类
     */
    public TreeNode Mirror (TreeNode pRoot) {
    
    
        // write code here
        // 根节点直接返回
        if(pRoot == 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/weixin_43957211/article/details/114674970