Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
就是翻转二叉树,递归处理。
public class InvertBinaryTree {
public TreeNode invertTree(TreeNode root) {
if (root == null)
return null;
if (root.left == null && root.right == null)
return root;
// 建立一个临时节点,将根节点的左右子树对调
TreeNode p;
p = root.left;
root.left = root.right;
root.right = p;
// 递归对调左右子树中的节点
invertTree(root.left);
invertTree(root.right);
return root;
}
}