Title: Please complete a function, enter a binary tree, the function output its mirror
The structure of the binary tree is defined as:
Package utils;
public class Binarytreenode {public
int value;
Public Binarytreenode Leftnode;
Public Binarytreenode Rightnode;
Public Binarytreenode () {
} public
binarytreenode (int value) {
this.value = value;
This.leftnode = null;
This.rightnode = null;
}
}
The image of the tree is a relatively new concept, we may not be able to find out the image of the tree in a single way. In order to make an intuitive impression, we can draw a binary tree by ourselves, and then draw a mirror image based on the experience of the mirror.
As the picture shows: The two-fork tree on the right is the mirror of the Left tree
Carefully analyze the characteristics of the two trees to see if you can summarize the steps to find a mirror. The root nodes of the two trees are the same, but their left and right two child nodes exchange positions. So let's start by swapping the two subnodes of the root node in the tree to get the next tree
After swapping the two child nodes of the root node, we notice that the child nodes of the node with the 10,6 value are still intact, so we also need to exchange the left and right subnodes of the two nodes. The results of the swap are the third and fourth trees. After these two exchanges, we have traversed all the non-leaf nodes. The tree after the swap is just the mirror of the original tree.
Summing up the above process, we draw the process of seeking a mirror image of a tree: Our previous sequence traverses each node of the tree, and if the node that is traversed has a child, it swaps its two subnodes, and after swapping all the left and right subnodes of the non-leaf node, we get a mirror image.
Implemented in Java code:
/**
* Topic: Please complete a function, enter a binary tree, the function output its mirror.
* *
package swordforoffer;
Import Utils. Binarytreenode;
/**
* @author Jinshuangqi
* *
* August 1, 2015/public
class E19mirrorofbinarytree {public
void Mirrorrecursively (Binarytreenode node) {
if (node = null) return
;
if (Node.leftnode = = NULL && Node.rightnode = null) return
;
Binarytreenode temp = Node.leftnode;
Node.leftnode = Node.rightnode;
Node.rightnode = temp;
if (Node.leftnode!= null)
mirrorrecursively (node.leftnode);
if (Node.rightnode!= null)
mirrorrecursively (Node.rightnode);
}
}