dcddc

西米大人的博客

0%

翻转二叉树

题目描述

样例
1 1
/ \ /
2 3 => 3 2
/
4 4

思路

分治法。
对于当前节点root,先翻转左右节点,再递归左节点,然后递归右节点

必须先翻转再递归,即先当前节点,再左,再右的顺序。思考一下你就懂了!

代码

1
2
3
4
5
6
7
8
9
10
11
public void invertBinaryTree(TreeNode root) {
// write your code here
if(root == null) {
return;
}
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
invertBinaryTree(root.left);
invertBinaryTree(root.right);
}

考察点

  • 二叉树
  • 分治法