leetcode - 43. 二叉树的直径

leetcode - 43. 二叉树的直径,第1张

leetcode - 43. 二叉树的直径 题目

代码
#include 
#include 
using namespace std;

typedef struct TreeNode{
	int val;
	struct TreeNode *left, *right;
}TreeNode, *BiTree;

void create(BiTree &root){
	int tn;
	cin>>tn;
	if(tn == -1){
		root = NULL;
		return;
	}
	root->val = tn;
	create(root->left);
	create(root->right);
}

int ans;

int depth(TreeNode *root){
	if(!root){
		return 0;
	}
	int left = depth(root->left);
	int right = depth(root->right);
	ans = max(ans, left + right + 1);
	return max(left, right)+1;
}

int diameterOfBinaryTree(TreeNode* root) {
	if(!root){
		return 0;
	}
	ans = 1;
	depth(root);
	return ans - 1;
}

int main(){
	TreeNode* root;
	int res;
	create(root);
	res = diameterOfBinaryTree(root);
	cout<<res;
	return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/676393.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-19
下一篇2022-04-19

发表评论

登录后才能评论

评论列表(0条)

    保存