题目
翻转二叉树
样例
解题思路
自顶向下开始翻转,到叶子节点结束。
故可使用递归来实现。
考虑特殊情况:
若root为null,则停止;
然后找到边界条件:
当left和right都为null时停止(即当此节点为叶子节点时停止)。
代码实现
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public void invertBinaryTree(TreeNode root) {
// write your code here
if(root == null || (root.left == null && root.right == null))
return;
else{
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertBinaryTree(root.left);
invertBinaryTree(root.right);
}
}