LeetCode226翻转二叉树

题目链接

https://leetcode-cn.com/problems/invert-binary-tree/

题解一

  • 递归解法
  • 我写的,不够简洁
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Problem: LeetCode 226
// URL: https://leetcode-cn.com/problems/invert-binary-tree/
// Tags: Tree Recursion
// Difficulty: Easy

#include <iostream>
using namespace std;

struct TreeNode{
TreeNode* left;
TreeNode* right;
int val;
TreeNode(int x):val(x),left(nullptr),right(nullptr){}
};

class Solution{
public:
TreeNode* invertTree(TreeNode* root) {
// 递归出口,空结点直接返回
if(root==nullptr)
return nullptr;
// 该结点交换左右子树
TreeNode *temp = root->left;
root->left = root->right;
root->right = temp;
// 递归翻转左右子树
invertTree(root->left);
invertTree(root->right);
return root;
}
};

题解二

  • 比我写的简洁一些,交换了最后两步的顺序,特别是利用了二叉树翻转后根结点不变的特点
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Problem: LeetCode 226
// URL: https://leetcode-cn.com/problems/invert-binary-tree/
// Tags: Tree Recursion
// Difficulty: Easy

#include <iostream>
using namespace std;

struct TreeNode{
TreeNode* left;
TreeNode* right;
int val;
TreeNode(int x):val(x),left(nullptr),right(nullptr){}
};

class Solution{
public:
TreeNode* invertTree(TreeNode* root) {
// 递归出口,空结点直接返回
if(root==nullptr)
return nullptr;
// 递归翻转左右子树
TreeNode* left = invertTree(root->left);
TreeNode* right = invertTree(root->right);
// 该结点交换左右子树
root->left = right;
root->right = left;
return root;
}
};

作者:@臭咸鱼

转载请注明出处:https://www.cnblogs.com/chouxianyu/

欢迎讨论和交流!