Sword refers to the offer face question 19
New Ket Network realism address: https://www.nowcoder.com/questionTerminal/564f4c26aa584921bc75623e48ca3011
Time limit: 1 seconds space limit: 32768K algorithm knowledge video explanation operation of the given two fork tree, transform it into the source binary tree mirroring.
Enter a description:
Binary tree Mirroring definition: source binary tree
8
/ \
6
/\ /\
5 7 9
Mirror binary tree
8
/ \ 6
/ //
9 7 5
Import Java.util.Stack;
public class Demo2 {
/* Method One: Recursive implementation
* When the recursion depth is deep enough, the computer crashes/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);
}
/
* Method Two: Loop implementation ———— use stack
/public void Mirror_cir (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);
}
}
Class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
Public TreeNode (int val) {
this.val = val;}}}