LeetCode:Path Sum - 樹的根節點到葉節點的數字之和

一、題目名稱java

Path Sum(樹的根節點到葉節點的數字之和)code

二、題目地址遞歸

https://leetcode.com/problems/path-sum/leetcode

三、題目內容開發

英文: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.get

中文:給定一顆二叉樹,若是從根節點到某一葉節點的路徑上數字之和等於指定的數字,返回真,不然返回假。io

例如:給定數字22,樹的結構爲class

5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

能夠找到路徑5->4->11->2,使5+4+11+2=22,所以返回真二叉樹

四、解題方法搜索

本題能夠使用遞歸,經過深度優先搜索(DFS)的方法解決。Java代碼以下:

/**
 * @功能說明:LeetCode 112 - Path Sum
 * @開發人員:Tsybius2014
 * @開發時間:2015年10月1日
 */
public class Solution {
    
    /**
     * 檢查一棵樹中,是否有一條路讓根節點到葉節點各節點值之和爲指定數字
     * @param root 樹的根節點
     * @param sum 指定數字
     * @return true:有這樣的路;false:沒有這樣的路
     */
    public boolean hasPathSum(TreeNode root, int sum) {
        
        if (root == null) {
            return false;
        }
        
        if (root.left == null && root.right == null) {
            //葉節點的狀況
            if (root.val == sum) {
                return true;
            } else {
                return false;
            }
        } else { 
            //非葉節點的狀況
            return hasPathSum(root.left, sum - root.val) || 
                hasPathSum(root.right, sum - root.val);
        }
    }
}

END

相關文章
相關標籤/搜索