543. 二叉树的直径(C++题解含VS可运行源码)

1.题解

递归

  • 利用递归,对每一个根节点,计算其左边的深度和右边的深度,
  • 左右深度相加即为当前子树的直径,遍历完每一棵子树后最大的那个直径即为二叉树的直径。
  • maxd = max(Left + Right, maxd);//关键代码

2.力扣C++源码

/**
 * Definition for a binary tree node.
 * 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:
    int maxd = 0;
    int diameterOfBinaryTree(TreeNode* root) {
        depth(root);
        return maxd;
    }
    int depth(struct TreeNode* root) {//求二叉树各个根节点深度
        if (root == NULL) return 0;
        int Left = depth(root->left);
        int Right = depth(root->right);
        maxd = max(Left + Right, maxd);//将每个节点最大直径(左子树深度+右子树深度)当前最大值比较并取大者
        return max(Left, Right) + 1;//返回节点深度
    }
};

3.VS可运行源码

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<limits>
#include<algorithm>
#include<math.h>
#pragma warning(disable:4996)
using namespace std;

struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};
//利用递归,对每一个根节点,计算其左边的深度和右边的深度,
//左右深度相加即为当前子树的直径,遍历完每一棵子树后最大的那个直径即为二叉树的直径。
//maxd = max(Left + Right, maxd);关键代码
int maxd = 0;
int depth(struct TreeNode* root) {//求二叉树各个根节点深度
    if (root == NULL) return 0;
    int Left = depth(root->left);
    int Right = depth(root->right);
    maxd = max(Left + Right, maxd);//将每个节点最大直径(左子树深度+右子树深度)当前最大值比较并取大者
    return max(Left, Right) + 1;//返回节点深度
}
int diameterOfBinaryTree(struct TreeNode* root) {
    depth(root);
    return maxd;
}

//递归方式创建与遍历
void CreateBiTree1(TreeNode** T)//传的是根指针的指针,这样不用返回值了就
{
    int val;
    scanf("%d", &val);
    if (val == -1)//将叶子节点都设为-1,作为判断输入终止标志,#这个根节点就是NULL
        *T = NULL;//*T就是BiTree T的T或者是BiTNode* T的T
    else
    {
        *T = (TreeNode*)malloc(sizeof(TreeNode));
        if (!*T)//开辟空间失败就退出
            exit(-1);
        (*T)->val = val;
        CreateBiTree1(&(*T)->left);//递归创建
        CreateBiTree1(&(*T)->right);
    }
}
int main()
{
    printf("按先序遍历顺序输入二叉树(叶子节点的左右孩子节点均输入-1):\n");
    TreeNode* T;
    CreateBiTree1(&T);//地址传递,传根节点指针的地址
    int ans = diameterOfBinaryTree(T);
    printf("二叉树的直径为:%d", ans);

	printf("\n");
	system("pause");
	return 0;
}

更多推荐