leetcode_687. 最長同值路徑(C++)

題目

原題鏈接

給定一個二叉樹,找到最長的路徑,這個路徑中的每個節點具有相同值。 這條路徑可以經過也可以不經過根節點。

注意: 兩個節點之間的路徑長度由它們之間的邊數表示。

示例 1:

輸入:

          5
         / \
        4   5
       / \   \
      1   1   5

輸出:

2

示例 2:

輸入:

      1
     / \
    4   5
   / \   \
  4   4   5

輸出:

2

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

思路

需要注意的是,題目中有一點沒講清楚,一條路徑也有可能是包括了一個節點的左右兒子的,如:示例二中的 4->4->4

那怎麼解決這個問題呢?

注:以下說的“箭頭”,指的是一條特殊的同值路徑,該路徑中的所有節點都只有一個子節點與自己同在該路徑中。

定義一個函數,該函數有兩個參數,一個是當前節點的指針,另一個是返回的答案。定義 l 是左子樹的最長箭頭的長度,r 爲右子樹的最長箭頭的長度,lnum存儲經過當前節點並向左延伸的箭頭的長度,rnum存儲經過當前節點並向右延伸的箭頭的長度。接下來進行特判:

  • if(當前節點與左兒子的值相等) lnum=l+1(注:下面代碼中的“+1”在末尾體現)
  • if(當前節點與右兒子的值相等)rnum=r+1(注:下面代碼中的“+1”在末尾體現)
  • (對於以上兩個選項都有效)否則,lnum,runm取值爲零
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int longestUnivaluePath(TreeNode* root) {
        int count = 0;
        findMax(root, count);
        return count;
    }
    int findMax(TreeNode* root, int& count) {
        if(!root) return 0;
        int l = findMax(root -> left, count);
        int r = findMax(root -> right, count);

        int lnum = 0, rnum = 0;
        if(root -> left && root -> left -> val == root -> val)
            lnum = l;
        if(root -> right && root -> right -> val == root -> val)
            rnum = r;
        count = max(count, lnum + rnum);
        return max(lnum, rnum) + 1;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章