您的位置:首页 > 编程语言 > C语言/C++

[LeetCode]226. Invert Binary Tree(反转二叉树)

2017-03-23 01:15 435 查看

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.csdn.net/booirror/article/details/46496719
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c++ 226