描述
翻转一棵二叉树
样例
Example 1:
Input: {1,3,#}
Output: {1,#,3}
Explanation:
1
/
3
Example 2:
Input: {1,2,3,#,#,4}
Output: {1,3,2,#,4}
Explanation:
1 1
/ \ / \
2 3 => 3 2
/ \
4 4
算法思路
通过递归的方式实现
代码实现(JAVA)
class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int val) {
this.val = val;
this.left = this.right = null;
}
}
public void invertBinaryTree(TreeNode root) {
if (root == null) {
return;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertBinaryTree(root.left);
invertBinaryTree(root.right);
}