编程语言
首页 > 编程语言> > 翻转二叉树(c++&&golang)

翻转二叉树(c++&&golang)

作者:互联网

#include <bits/stdc++.h>
using namespace std;

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

class Solution
{
public:
    TreeNode *invertTree(TreeNode *root)
    {
        if (root == nullptr)
        {
            return nullptr;
        }

        //翻转左右子树
        TreeNode *pTemp = root->left;
        root->left = root->right;
        root->right = pTemp;

        //遍历左子树
        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
};
package main

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func invertTree(root *TreeNode) *TreeNode {
	//结束条件
	if root == nil {
		return nil
	}

	//翻转左右节点
	temp := root.Left
	root.Left = root.Right
	root.Right = temp

	//翻转左子树
	invertTree(root.Left)
	//翻转右子树
	invertTree(root.Right)
	return root
}

标签:right,TreeNode,invertTree,nullptr,golang,二叉树,&&,root,left
来源: https://blog.csdn.net/weixin_43021844/article/details/122193465