題目:node
Invert a binary tree.this
4 / \ 2 7 / \ / \ 1 3 6 9
tospa
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.
解決:get
① 直接遞歸交換左右子樹。it
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution { //0ms
public TreeNode invertTree(TreeNode root) {
if(root == null) return null;
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
invertTree(root.left);
invertTree(root.right);
return root;
}
} io
② 在discuss部分看到了使用dfs實現交換,須要建立一個新的tree用於保存交換後的樹。class
public class Solution { //0ms
public TreeNode invertTree(TreeNode root) {
if(root == null) return null;
TreeNode invertedRoot = new TreeNode(0);
getInvertTree(root, invertedRoot);
return invertedRoot;
}
public void getInvertTree(TreeNode root, TreeNode invertedRoot){
if(root == null) return;
invertedRoot.val = root.val;
if(root.left != null){
invertedRoot.right = new TreeNode(0);
getInvertTree(root.left, invertedRoot.right);
}
if(root.right != null){
invertedRoot.left = new TreeNode(0);
getInvertTree(root.right, invertedRoot.left);
}
}
}di