Sword refers to Offer 27. Mirror of Binary Tree-Recursion/Stack

Sword refers to Offer 27. The mirror image of the binary tree

Method one: recursion

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root!=null){
            TreeNode tmp=root.left;
            root.left=root.right;
            root.right=tmp;
            mirrorTree(root.left);
            mirrorTree(root.right);
        }
        return root;
    }
}

Method 2: Stack

Stack usage, stack.push(xxx)

stack.isEmpty()

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root==null)  return null;
        Stack<TreeNode> stack=new Stack<TreeNode>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node=stack.pop();
            if(node.left!=null)    stack.push(node.left);
            if(node.right!=null)    stack.push(node.right);
            TreeNode tmp=node.left;
            node.left=node.right;
            node.right=tmp;
        }
        return root;
    }
}

Guess you like

Origin blog.csdn.net/qq_41041762/article/details/108077596