Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1递归:为啥我的代码总这么丑
/**
* 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;
else if(root.left == null){
root.left = invertTree(root.right);
root.right = null;
}
else if (root.right == null){
root.right = invertTree(root.left);
root.left = null;
}
else{
TreeNode tmp = invertTree(root.left);
root.left = invertTree(root.right);
root.right = tmp;
}
return root;
}
}
非递归方法待续