1. 问题描述:
旋转一颗二叉树(每一个节点的左右子数都要交换)
2. 解答:
这题没看答案之前我是用后序遍历(先左后右最后中)去做的,很奇怪自己为什么没有一开始就想到更符合直觉的先序遍历~~~
本人算法的伪代码 :
function invert (root)
if root为空 then
end function
end if
invert(root左子树)
invert(root右子树)
交换root左右子树
end function
相应的java代码:

1 public class Solution { 2 public TreeNode invertTree(TreeNode root) { 3 if (root == null) 4 return root; 5 TreeNode lt = root.getLeft(); 6 TreeNode rt = root.getRight(); 7 8 invertTree(lt); 9 invertTree(rt); 10 TreeNode temp = lt; 11 root.setLeft(rt); 12 root.setRight(temp); 13 14 return root; 15 } 16 }
在看一下网上先序遍历算法的伪代码:
function invert(root):
if root为空
end function
end if
交换root左右子树
invert(root左子树)
invert(root右子树)
end function