Mirror image of a binary tree

前端 未结 13 2566
时光取名叫无心
时光取名叫无心 2020-12-01 09:00

Suppose there is a tree:

             1
            / \\
           2   3
              / \\
             4   5

Then the mirror image will

13条回答
  •  孤街浪徒
    2020-12-01 09:24

    Recursive and Iterative methods in JAVA: 1) Recursive:

        public static TreeNode mirrorBinaryTree(TreeNode root){
    
        if(root == null || (root.left == null && root.right == null))
            return root;
    
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
    
        mirrorBinaryTree(root.left);
        mirrorBinaryTree(root.right);
    
    
        return root;
    
    }
    

    2) Iterative:

    public static TreeNode mirrorBinaryTreeIterative(TreeNode root){
        if(root == null || (root.left == null && root.right == null))
            return root;
    
        TreeNode parent = root;
        Stack treeStack = new Stack();
        treeStack.push(root);
    
        while(!treeStack.empty()){
            parent = treeStack.pop();
    
            TreeNode temp = parent.right;
            parent.right = parent.left;
            parent.left = temp;
    
            if(parent.right != null)
                treeStack.push(parent.right);
            if(parent.left != null)
                treeStack.push(parent.left);
        }
        return root;
    }
    

提交回复
热议问题