<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                ## 一.題目描述 Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example:? Given the below binary tree and sum = 22, ~~~ 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 ~~~ return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. ## 二.題目分析 這道題屬于深度優先搜索的范疇,通過分別計算二叉樹的左右子樹是否的和是否等于sum-root->val來進行深度優先搜索,只有到達也結點搜索才結束,因此,遞歸的退出條件就是到達葉結點,同時,也要考慮輸入是空指針的情況,這種情況返回false值。同時,由于只要判斷是否存在,而不用找到每一個這樣的路徑,因此,只要左子樹滿足條件時,就可以直接返回,不需要處理右子樹,這樣就可以進行剪枝,減少計算的復雜度。 遞歸做法的時間復雜度為O(n),空間復雜度為O(logn)。 ## 三.示例代碼 ~~~ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if (!root) { return false; } if (!root->left && !root->right && root->val == sum) { return true; } int SumChild = sum - root->val; if (hasPathSum(root->left, SumChild)) { return true; } if (hasPathSum(root->right, SumChild)) { return true; } return false; } }; ~~~ ## 四.小結 該題屬于二叉樹深度優先搜索問題,可以通過遞歸來實現。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看