19. 二叉树镜像

题目

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

思路

先前序遍历这棵树的每个结点,如果遍历到的结点有子结点,就交换它的两个子节点,当交换完所有的非叶子结点的左右子结点之后,就得到了树的镜像。显然可以利用递归或者借助栈遍历二叉树来实现。

package com.zhumq.leetcode;
import java.util.ArrayDeque;
import java.util.Deque;
public class SymmetricTree {
    /**
     * 思路1:用栈遍历二叉树
     */
    public void Mirror1(TreeNode root) {
        if (root == null) {
            return;
        }
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.push(root);
        while (!deque.isEmpty()) {
            TreeNode node = deque.pop();
            if (node.left != null || node.right != null) {
                TreeNode temp = node.left;
                node.left = node.right;
                node.right = temp;
            }
            if (node.left != null) {
                deque.push(node.left);
            }
            if (node.right != null) {
                deque.push(node.right);
            }
        }


    }

    /**
     * 思路2:递归
     */
    public void Mirror2(TreeNode root) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            return;
        }
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        if (root.left != null) {
            Mirror2(root.left);
        }
        if (root.right != null) {
            Mirror2(root.right);
        }
    }

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

    //递归使用数组创建树
    public TreeNode createBinaryTreeByArray(int[] array, int index) {
        TreeNode tn = null;
        if (index < array.length) {
            int value = array[index];
            tn = new TreeNode(value);
            tn.left = createBinaryTreeByArray(array, 2 * index + 1);
            tn.right = createBinaryTreeByArray(array, 2 * index + 2);
            return tn;
        }
        return tn;
    }
    
	public static void main(String[] args) {
        SymmetricTree sy = new SymmetricTree();
        int[] array = {8, 6, 10, 5, 7, 9, 11};
        TreeNode treeNode = sy.createBinaryTreeByArray(array, 0);
        System.out.println(treeNode.left.right.val);
        sy.Mirror1(treeNode);
        System.out.println(treeNode.left.right.val);
    }
}

猜你喜欢

转载自blog.csdn.net/DjokerMax/article/details/82968787