Invert a binary tree.
4 / 2 7/\ /1 3 6 9
To
4 / 7 2/\ /9 6 3 1
What about this problem =. = It's interesting to look at the topic profile. hahaha. ~ To be honest, I really hate whiteboard directly to the code.
Because the BTS to be flipped has been given out, Gray often short of a ah ~ so according to their own preferences whatever exchange is good.
Because the BTS has been given here so can be lazy direct exchange (after all, so short), this comparison trickery. The code is as follows.
public class Solution {public TreeNode inverttree (TreeNode root) { //invert directlytreenode left=root.left; TreeNode Right=root.right;root.left=inverttree (right), Root.right=inverttree (left), return root; Special Case if (root==null) { return null;}} }
And then stick to a conventional mindset, which is on the Program Creek. I probably wrote a little bit, too lazy to run. Just put a definite accepted answer.
This is a solid one to see.
Public TreeNode inverttree (TreeNode root) { linkedlist<treenode> queue = new linkedlist<treenode> (); if (root!=null) { queue.add (root); } while (!queue.isempty ()) { TreeNode p = queue.poll (); if (p.left!=null) queue.add (p.left); if (p.right!=null) queue.add (p.right); TreeNode temp = p.left; P.left = p.right; P.right = temp; } return root; }
[Leetcode] Invert Binary Tree