[LeetCode]
(https://leetcode.com/problems/invert-binary-tree/)](https://leetcode.com/problems/invert-binary-tree/)
Total Accepted: 87629 Total Submissions: 193029 Difficulty: Easy
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
二叉树翻转。
这个要明白递归。
递归很重要的是递归终止的条件。在这个题目中不断地翻转每隔一个节点的左右节点,当要翻转的节点是空,停止翻转返回null。
其实可以更聪明一点,如果节点的子节点为空就不去翻转,但是效率应该差距不大。
这个递归的运行情况是这样的:
翻转root的左右子节点。一直翻转root左子节点直到结束,再一直翻转root右节点直到结束。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null){
return null;
}
TreeNode temp=root.left;
root.left=root.right;
root.right=temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
2016/4/29 21:58:13