C++翻转二叉树——LeetCode

来源:力扣(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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值