剑指offer17-二叉树的镜像

86 阅读1分钟

二叉树的镜像

题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。

思路1

  • 递归
程序
    /**
     * code1
     * 时间复杂度:O(),空间复杂度:O()
     */
public class Solution {
    public void Mirror(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)
        Mirror(root.left);
        if(root.right != null)
        Mirror(root.right);
    }
}
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}
*/

思路2

程序
import java.util.Stack;
public class Solution {
    public void Mirror(TreeNode root) {
        if (root == null) {
            return ;
        }
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                TreeNode temp = root.left;
                root.left = root.right;
                root.right = temp;
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            root = root.right;
        }
    }
    }