Invert a binary tree.
4 / 2 7/\ /1 3 6 9
To
4 / 7 2/\ /9 6 3 1
Trivia:
This problem is inspired by this original tweets by Max Howell:
google:90% of our engineers with the software you wrote (Homebrew), but can ' t invert a binary tree on a Whitebo ard so fuck off.
The
code is as follows:
/** * Definition for a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {public TreeNode inverttree (TreeNode root) {if (root = null | | (Root.left = = null) && (root.right = = null)) return ROOT;ROOT=INVERTTREELR (Root,root.left, root.right); return Root;} Public TreeNode INVERTTREELR (TreeNode Root,treenode left, TreeNode right) {//left,right bit temporary reference if (left = = null && Right! = null) {left = Right;right = NULL;LEFT=INVERTTREELR (Left,left.left, left.right);} else if (left! = null && right = = null) {right = Left;left = NULL;RIGHT=INVERTTREELR (Right,right.left, right.right);} else if (left = = null && Amp right = = null) {}else {TreeNode tmp = Null;tmp = Left;left = Right;right = TMP;LEFT=INVERTTREELR (Left,left.left, Left.right ); Right=inverttreelr (Right,right.left, right.right);} Root.left=left;root.right=right;return root;}}
Operation Result:
(easy) Leetcode 226.Invert Binary Tree