您的位置:首页 > 其它

[LeetCode] 226 翻转二叉树

2016-02-28 00:40 405 查看

Invert Binary Tree(翻转二叉树)

【难度:Easy】

Invert a binary tree.



to



对一棵二叉树进行镜像翻转。

解题思路

根据二叉树的结构特点,使用递归的思想,在根节点root非空时,分别对左子树和右子树进行递归操作,更换root->left和root->right的值,由局部到整体完成整棵二叉树的翻转。

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) {
TreeNode* tmp = invertTree(root->left);
root->left = invertTree(root->right);
root->right = tmp;
}
return root;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: