0
点赞
收藏
分享

微信扫一扫

226. Invert Binary Tree

王远洋 2022-08-03 阅读 66


Invert a binary tree.

     4
/ \
2 7
/ \ / \
1 3 6 9

to

     4
/ \
7 2
/ \ / \
9 6 3 1

Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

/**
* 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) {
return null;
}

TreeNode tempNode = root.left;
root.left = root.right;
root.right = tempNode;

invertTree(root.left);
invertTree(root.right);

return root;
}
}

/**
* 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)
return root;
TreeNode curr = new TreeNode(root.val);
curr.right = invertTree(root.left);
curr.left = invertTree(root.right);
return curr;
}
}


举报

相关推荐

0 条评论