Leetcode687. 最長同值路徑(二叉樹遍歷,求最長路徑,遍歷保存優化)

鏈接:https://leetcode-cn.com/problems/longest-univalue-path

給定一個二叉樹,找到最長的路徑,這個路徑中的每個節點具有相同值。 這條路徑可以經過也可以不經過根節點。
注意:兩個節點之間的路徑長度由它們之間的邊數表示。

示例 1:
輸入:

      5
     / \
    4   5
   / \   \
  1   1   5

輸出:
2

示例 2:
輸入:

      1
     / \
    4   5
   / \   \
  4   4   5

輸出:
2
注意: 給定的二叉樹不超過10000個結點。 樹的高度不超過1000。

**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

 /* 思路
 * 二叉樹的每個節點爲根節點展開遍歷,判斷最大值
 * 提高: 保存每次遍歷的值
 */

int search_tree_root(struct TreeNode* root){ 
    if(NULL == root){return 0;}

    static int root_flag = 0; 
    int tmp_flag = root_flag; // tmp_flag == 0 時回到根節點

    int left = 0;
    int right = 0;
    if(NULL != root->left && root->val == root->left->val){
        root_flag++;
        left = search_tree_root(root->left) + 1;
    }
    if(NULL != root->right && root->val == root->right->val){
        root_flag++;
        right = search_tree_root(root->right) + 1;
    }

    // 只有進入的根節點可以左右子樹相加求最長路徑,子樹需要判斷左右子樹最長路徑,取最長
    if(0 == tmp_flag){
        root_flag = 0;  // 提交測試時,max被多個例子修改了,所以這個地方需要讓root_flag置0
        return left + right;
    }
    return left > right ? left : right;
    
}

int longestUnivaluePath(struct TreeNode* root){
    if(NULL == root){return 0;}

    static int max = 0;

    int ret = search_tree_root(root);
    if(max < ret){ max = ret;}

    int left;
    int right;
    left = longestUnivaluePath(root->left);
    right = longestUnivaluePath(root->right);

    if(max < left){ max = left;}
    if(max < right){ max = right;}

    // 提交測試時,max被多個例子修改了,所以這個地方需要讓max置0
    int tmp = max;
    max = 0;
    return tmp;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章