1. 程式人生 > 實用技巧 >LeetCode543二叉樹的直徑

LeetCode543二叉樹的直徑

題目連結

https://leetcode-cn.com/problems/diameter-of-binary-tree/

題解

  • 一棵二叉樹的直徑長度是任意兩個結點路徑長度中的最大值,兩結點之間的路徑長度是以它們之間邊的數目表示
  • 將一條路徑分為左右兩半,兩個結點之間路徑長度等於根節點左右子樹的深度之和
  • 這條路徑可能穿過也可能不穿過根結點,所以在DFS過程中記錄路徑長度的最大值
// Problem: LeetCode 543
// URL: https://leetcode-cn.com/problems/maxDiameter-of-binary-tree/
// Tags: Tree DFS Recursion
// Difficulty: Easy

#include <iostream>
#include <algorithm>
using namespace std;

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

class Solution{
private:
    int maxDiameter=0;
    int depth(TreeNode* root){
        // 空節點深度為0
        if(root==nullptr)
            return 0;
        // 左右子樹深度
        int leftDepth = depth(root->left);
        int rightDepth = depth(root->right);
        // 更新最大直徑
        if (leftDepth + rightDepth > this->maxDiameter)
            this->maxDiameter = leftDepth + rightDepth;
        // 返回該樹深度
        return max(leftDepth, rightDepth) + 1;
    }

public:
    int diameterOfBinaryTree(TreeNode* root) {
        depth(root);
        return this->maxDiameter;
    }
};

作者:@臭鹹魚

轉載請註明出處:https://www.cnblogs.com/chouxianyu/

歡迎討論和交流!