標籤:二叉樹 路徑 演算法 面試 java
【112-Path Sum(路徑和)】
【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】
原題
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.
題目大意
給定一棵二叉樹和一個和,判斷從樹的根結點到葉子結點的所有結點的和是否等於給定的和,如果等於,就返回true,否則返回false。
解題思路
對樹進行遍曆,並且使用回溯法進行求解。
代碼實現
樹結點類
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}
演算法實作類別
public class Solution { private boolean stop = false; // 判斷是否已經找到答案 public boolean hasPathSum(TreeNode root, int sum) { calculate(root, 0, sum); return stop; } /** * 計算根到葉子結點的和 * @param node 當前處理的節點 * @param cur 從根節點到當前結點之前的所有節點和 * @param sum 要求的和 */ private void calculate(TreeNode node, int cur, int sum) { if (!stop && node != null) { // 還沒有找到答案,並且要處理的節點不為空白 // 如果是分葉節點,就檢查從根到當前分葉節點的和是否為sum,如果是就說明已經找到,改變stop if (node.left == null && node.right == null && (node.val + cur == sum) ) { stop = true; } // 如果是非分葉節點,繼續處理 if (node.left != null) { calculate(node.left, cur + node.val, sum); } if (node.right != null) { calculate(node.right, cur + node.val, sum); } } }}
評測結果
點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。
特別說明
歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47414069】
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
【LeetCode-面試演算法經典-Java實現】【112-Path Sum(路徑和)】