Title Descriptionoperates a given two-fork tree and transforms it into a mirror of the source binary tree.
Input Description:
Image definition of binary tree: source binary tree 8 /6 x / \ 5 7 9 Mirror binary tree 8 / 6 /\ / 9 7 5
Code Listing 1:recursive method, the memory is easy to explode when the recursion depth is large
<span style= "FONT-SIZE:18PX;" >/**public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; Public TreeNode (int val) { this.val = val; }} */public class Solution {public void Mirror (TreeNode root) { if (root==null) { return; } TreeNode temp; Temp=root.left; Root.left=root.right; Root.right=temp; Mirror (root.left); Mirror (root.right); }} </span>
Code Listing 2:traversal from the root node, using stacks to implement
<span style= "FONT-SIZE:18PX;" >import java.util.*;p Ublic class Solution {public void Mirror (TreeNode root) { if (root==null) { return; } Stack<treenode> stack=new stack<treenode> (); Stack.push (root); while (!stack.isempty ()) { TreeNode node=stack.pop (); if (node.left!=null| | Node.right!=null) { 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);}}} </span>
The mirror of the binary tree of the offer (34) of the sword