原题链接:https://leetcode.com/problems/invert-binary-tree/description/
这是一道有历史典故的算法题目哦:
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
TreeNode root = new TreeNode(4);
root.left = new TreeNode(2);
root.left.left = new TreeNode(1);
root.left.right = new TreeNode(3);
root.right = new TreeNode(7);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(9);
root = s.invertTree(root);
System.out.println(root);
}
/**
* 这道题目还是有历史典故的,下面我的实现是其递归实现版本,也就是做深度优先遍历吧,这也是官方答案的第一种。
* 官方答案第二种就是使用一个队列来做广度优先遍历来进行处理吧,这里就不在说了!
*
* @param root
* @return
*/
public TreeNode invertTree(TreeNode root) {
if (root == null || (root.left == null && root.right == null)) {
return root;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}