翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
思路:1、递归思想,如果存在左右子树,那么就翻转
代码:
public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } if (root.right != null || root.left != null) { TreeNode temp = root.left; root.left = root.right; root.right = temp; if (root.right != null) { invertTree(root.right); } if (root.left != null) { invertTree(root.left); } } return root; }