问题描述
翻转一棵二叉树。
示例
4
/ \
2 7
/ \ / \
1 3 6 9
4
/ \
7 2
/ \ / \
9 6 3 1
思路
对于某个非空结点,交换它的左右孩子。
如果空节点,什么都不做。
解决方案
class Solution {
public TreeNode invertTree(TreeNode root) {
test(root);
return root;
}
private void test(TreeNode root){
if(root == null){
return;
}
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
test(root.left);
test(root.right);
}
}