226. Invert Binary Tree
Invert a binary tree.反转二叉树
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
用递归,交换各个节点的左右节点
代码如下:
C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
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;
}
};
当然,非递归更好,查阅了一些非递归方法,讲解很详细
链接1 http://www.2cto.com/kf/201506/410311.html
链接2 http://blog.youkuaiyun.com/booirror/article/details/46496719