来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/invert-binary-treed
题目:
代码
#include <iostream>
#include<cstdlib>
#include<vector>
using namespace std;
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;//如果这个节点是空,说是叶子节点,不用翻转,直接返回原值就好了
//或者return root;
TreeNode* temp;
temp = root->left;//只要有节点就交换地址,不管是不是只有一个节点,左节点一个或者右节点一个
root->left = root->right;//都要换,有的和NULL换,这样才符合题目要求
root->right = temp;//并没有说如果一个节点只有一个叶子节点就不交换
invertTree(root->left);
invertTree(root->right);
return root;
}
static int cnt;
int cntlen(TreeNode* root)
{
if (root != NULL)
{
cnt++;
cntlen(root->left);
cntlen(root->right);
}
else
return cnt;
}
};
int Solution::cnt = 0;
//vector<int> Solution::flipedvector();
int main()
{
TreeNode node[] = { 4, 2, 7, 1, 3, 6, 9 };
for (int i = 0; i < 6; i++)
cout << node[i].val << ' ';
node[0].left = &node[1];
node[0].right= &node[2];
node[1].left = &node[3];
node[1].right = &node[4];
node[2].left = &node[5];
node[2].right = &node[6];
cout << '\n' << endl;
Solution kill;
kill.invertTree(&node[0]);
int result;
result = kill.cntlen(&node[0]);
cout << "节点数:" << result << endl;
return 0;
}
结果:
还要再学一下二叉树的创建和遍历算法。
难题不会太难了,简单的题目正正好,o(╥﹏╥)o