【二叉樹】路徑總和

一、題目

力扣原題:https://leetcode-cn.com/problems/path-sum/

二、遞歸

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    private int target;

    private boolean result;

    public boolean hasPathSum(TreeNode root, int sum) {
        if (null == root) {
            return false;
        }

        this.result = false;
        this.target = sum;
        dfs(root, 0);
        return this.result;
    }

    private void dfs(TreeNode root, int cur) {
        if (null == root) {
            return;
        }

        cur = cur + root.val;
        if (cur == this.target && null == root.left && null == root.right) {
            this.result = true;
            return;
        }

        if (null != root.left) {
            dfs(root.left, cur);
        }

        if (null != root.right) {
            dfs(root.right, cur);
        }
    }
}
  • 時間複雜度:O(n)。DFS搜索,每個節點均會訪問到一次;
  • 空間複雜度:O(log(n))。最壞情況是二叉樹退化爲鏈表,此時時間複雜度爲O(n),最好情況是最小的樹深度O(log(n))。

三、強行總結

  • 遞歸是二叉樹常用的解題思路;
  • 本題關鍵是在第一時間可以意識到DFS搜索;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章