path_sum

題目描述

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,看存不存在一條路徑使得該路徑上的結點數值和等於sum。這裏只要求判斷是否存在一條路徑,path_sum2則是要求找出所有的路徑,這裏利用深度優先搜索(DFS)來解決,以給定例子爲例分析,判斷從根節點是否存在一條sum=22的路徑,相當於判斷從左兒子開始是否有一條22-5=17的路徑,或者從右兒子開始是否有一條22-8=14的路徑。

詳細代碼

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

    //題目強調是從root到葉子節點  注意葉子節點的定義
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null)
        {
            //空樹  結束條件之一
            return false;
        }
        else 
        {
            if(root.left==null && root.right==null)
            {
                //葉子節點 left right都爲空
                if(sum== root.val)
                {
                    return true;
                }
                else 
                {
                    return false;
                }
            }
            else 
            {
                //非葉子結點
                return hasPathSum(root.left, sum-root.val) | hasPathSum(root.right, sum-root.val);
            }

        }
    }

總結

此題目是關於BST和DFS的,前面word_ladder和word_ladder2 是關於graph的BFS(沒有建立圖,而是利用題目限制的條件進行搜索,否則超時),可以放在一起總結下,此題目還有path_sum2版本,要求算出所有的路徑,我會在接下來的文章中介紹。

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