Description
Invert a binary tree.
Example
1 1 / \ / 2 3 => 3 2 / 4 4
Problem solving: The topic requires to say two tree Saozi right sub-tree to swap, with the return to do very simple:
1 /**2 * Definition of TreeNode:3 * public class TreeNode {4 * public int val;5 * Public TreeNode left and right;6 * Public TreeNode (int val) {7 * This.val = val;8 * This.left = This.right = null;9 * }Ten * } One */ A - Public classSolution { - /** the * @paramroot:a TreeNode, the root of the binary tree - * @return: Nothing - */ - Public voidinvertbinarytree (TreeNode root) { + //Write your code here - if(Root = =NULL) + return ; ATreeNode left =Root.left; atTreeNode right =Root.right; -Root.left =Right ; -Root.right =Left ; - Invertbinarytree (root.left); - Invertbinarytree (root.right); - } in}
Non-recursive method:
1 Public classSolution {2 PublicTreeNode inverttree (TreeNode root) {3queue<treenode> q =NewLinkedlist<treenode>();4 if(root!=NULL) Q.offer (root);5 while(!Q.isempty ()) {6TreeNode Curr =Q.poll ();7TreeNode tmp =Curr.right;8Curr.right =Curr.left;9Curr.left =tmp;Ten if(curr.left!=NULL) Q.offer (curr.left); One if(curr.right!=NULL) Q.offer (curr.right); A } - returnRoot; - } the}
175. Invert Binary Tree "Lintcode by Java"