標籤:leetcode java 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 = 22,
5 / 4 8 / / 11 13 4 / \ 7 2 1
返回true ,因為樹中存在一條從根節點到葉子節點的路徑5->4->11->2 他們的和為22.
演算法分析:
方法一:
常規的遞迴方法來做,遞迴條件是看左子樹或者右子樹有沒有滿足條件的路徑,也就是子樹路徑和等於當前sum減去當前節點的值。結束條件是如果當前節點是空的,則返回false,如果是葉子,那麼如果剩餘的sum等於當前葉子的值,則找到滿足條件的路徑,返回true.
方法二:
這是典型的BFS(廣度優先搜尋)的題目,利用隊列。
將所有的節點儲存在一個隊列匯總,將節點值的和儲存在另外一個隊列中。當前節點如果為葉子節點時,檢查儲存的和值是否是目標值。
AC代碼:
方法一:
<span style="font-family:Microsoft YaHei;font-size:12px;"> //遞迴演算法public class Solution { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) { return false; } if (root.left == null && root.right == null) { if( sum - root.val == 0) { return true; } } return (hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val)); }</span>
方法二:
<span style="font-family:Microsoft YaHei;font-size:12px;">//非遞迴演算法public class Solution { public boolean hasPathSum(TreeNode root, int sum) { if(root == null) return false; LinkedList<TreeNode> nodes = new LinkedList<TreeNode>(); LinkedList<Integer> values = new LinkedList<Integer>(); nodes.add(root); values.add(root.val); while(!nodes.isEmpty()) { TreeNode curr = nodes.poll(); int sumValue = values.poll(); if(curr.left == null && curr.right == null && sumValue==sum) { return true; } if(curr.left != null) { nodes.add(curr.left); values.add(sumValue+curr.left.val); } if(curr.right != null) { nodes.add(curr.right); values.add(sumValue+curr.right.val); } } return false; }}</span>
著作權聲明:本文為博主原創文章,轉載註明出處
[LeetCode][Java] Path Sum