LeetCode 30天挑戰 Day-30

LeetCode 30 days Challenge - Day 30

本系列將對LeetCode新推出的30天算法挑戰進行總結記錄,旨在記錄學習成果、方便未來查閱,同時望爲廣大網友提供幫助。


Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree

Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree.

We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree.

Example 1:

Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,0,1]
Output: true
Explanation: 
The path 0 -> 1 -> 0 -> 1 is a valid sequence (green color in the figure). 
Other valid sequences are: 
0 -> 1 -> 1 -> 0 
0 -> 0 -> 0

Example 2:

Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,0,1]
Output: false 
Explanation: The path 0 -> 0 -> 1 does not exist, therefore it is not even a sequence.

Example 3:

Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,1]
Output: false
Explanation: The path 0 -> 1 -> 1 is a sequence, but it is not a valid sequence.

Constraints:

  • 1 <= arr.length <= 5000
  • 0 <= arr[i] <= 9
  • Each node’s value is between [0 - 9].

Solution

題目要求分析:給定一棵二叉樹以及一個整型數組,定義從根出發直到葉子結點結束的路徑爲一個有效序列,且整型數組按照元素位置連接成一個序列,求是否存在一個有效序列與數組確定的序列相同。

解法:

本題原題比較繞口、難以理解,實際上就是從二叉樹根出發,尋找一條直達葉子結點的路徑,路徑上每個結點值依次與給定的整型數組相等。

理解清楚題意後,本題就變得比較簡單,DFS即可解決。

這裏梳理一下DFS過程中的退出條件,以下稱數組確定的序列爲目標序列

  1. 當前位置已經超過數組長度:說明該路徑還沒到達葉子結點就已經超過目標序列的最大長度了,返回false
  2. 當前位置未超過數組長度,且沒有左右孩子,爲葉子結點:說明當前路徑是一個有效序列,且目標序列和該有效序列除了尾部元素其餘值一致。因此只需要判斷目標序列是否也到達尾部元素,尾部元素值是否與該葉子節點值相等,滿足則該有效序列即爲目標序列,返回true,反之返回false
  3. 當前位置未超過數組長度,且不是葉子結點,且該位置元素值不等於目標序列對應位置元素值:說明該路徑失效,返回false
  4. 當前位置未超過數組長度、不是葉子結點、該位置元素值等於目標序列對應位置元素值:說明迄今爲止的路徑都滿足目標序列的要求,需要接着往下考慮:對存在的孩子結點進行DFS,且只要有一個孩子滿足條件就返回true,都不滿足才返回false

以上解釋爲追求普適性,比較囉嗦,可以直接參考代碼,代碼可讀性較強。


bool dfs(TreeNode* node, vector<int> &arr, int pos) {
    if (pos > arr.size() - 1) return false;
    // leaf
    if (!node->left && !node->right) {
        return (pos == arr.size() - 1 && node->val == arr[pos]);
    }
    // non-leaf
    if (node->val != arr[pos]) return false;
    bool flag = 0;
    if (node->left) flag = dfs(node->left, arr, pos+1);
    if (node->right) flag = flag || dfs(node->right, arr, pos+1);
    return flag;
}
bool isValidSequence(TreeNode* root, vector<int>& arr) {
    return dfs(root, arr, 0);
}

傳送門:Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree

2020/4 Karl


本篇是LeetCode 30天挑戰系列的最後一篇,這三十天的堅持令我受益匪淺。如果讀者有機會看到這裏,不妨點進作者頭像參考整個系列的其他文章,也可參考作者個人博客同步內容,並自己動手練習,一定會有所收穫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章