543. Diameter of Binary Tree / 遞歸

題目描述

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Example:
Given a binary tree

          1
         / \
        2   3
       / \     
      4   5    

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

解析

按照常用方法計算一個節點的深度:max(depth of node.left, depth of node.right) + 1。在計算的同時,經過這個節點的路徑長度爲 1 + (depth of node.left) + (depth of node.right) 。搜索每個節點並記錄這些路徑經過的點數最大值,期望長度是結果 - 1。

class Solution {
public:
    int ans;
    int diameterOfBinaryTree(TreeNode* root) {
        ans=1;
        getHeight(root);
        return ans-1;
    }
    int getHeight(TreeNode* root){
        if(root==NULL) return 0;
        int l=getHeight(root->left),r=getHeight(root->right);
        ans=max(ans,l+r+1);
        return max(l,r)+1;
    }
};

類似題

124. Binary Tree Maximum Path Sum

Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

分析:這題的情況與上題有所不同,路徑不一定是越長值就越大,需要在找的過程中判斷路徑的值是大於0還是小於0,小於0就捨棄掉這一段。

class Solution {
public:
    int ans=INT_MIN;
    int maxPathSum(TreeNode* root) {
        maxPathUptoDown(root);
        return ans;
    }
    int maxPathUptoDown(TreeNode* root){
        if(root==NULL) return 0;
        int l=maxPathUptoDown(root->left);
        int r=maxPathUptoDown(root->right);
        int maxPath=root->val+max(0,l)+max(0,r);
        ans=max(ans,maxPath);
        return max(max(l,r),0)+root->val;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章