本文主要是介绍翻转二叉树(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
}
这篇关于翻转二叉树(c++&&golang)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!