Operates 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 10
/ \ / \
5 7 9 11
Mirrored binary Tree
8
/ \
10 6
/ \ / \
11 9 7 5
The code is as follows:
/** Public classTreeNode {intval =0; TreeNode Left=NULL; TreeNode Right=NULL; PublicTreeNode (intval) {this.val = val; }}*/import Java.util.Stack; Public classSolution { Publicstatic void Mirror (TreeNode root) {if(root==NULL) {return; }if(Root. Left==NULL&&root. Right==NULL) {return; } stack<treenode> Stacktree =NewStack<treenode> (); Stacktree.push (root); while(!stacktree.IsEmpty()) {TreeNode node= stacktree.pop (); System.out.println (Node.val);if(node. Left!=NULL|| Node. Right!=NULL) {TreeNode temp = node. Left; Node. Left= node. Right; Node. Right= temp; }if(node. Left!=NULL) {Stacktree.push (node. Left); }if(node. Right!=NULL) {Stacktree.push (node. Right); } } }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Sword finger offer--Two tree mirror