二叉树镜像(交换左右子树)

//非递归
public void mirror(TreeNode root)
{
    Stack<TreeNode> stack = new Stack<>();
    if(root == null) return;
    stack.push(root);
    while(!stack.isEmpty())
    {
        TreeNode node = stack.pop();
        TreeNode temp = node.left;
        node.left = node.right;
        node.right = temp;
        if(node.left != null) stack.push(node.left);
        if(node.right != null) stack.push(node.right);
    }
}

//递归 
public void mirror(TreeNode root)
{
    if(root == null) return;
    TreeNode temp = root.left;
    root.left = root.right;
    root.right = temp;
    mirror(root.left);
    mirror(root.right);
}

你可能感兴趣的:(二叉树镜像(交换左右子树))