Title
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such this adding up all the values along the Path equals the given sum.
For Example:
Given The below binary tree
sum = 22
and ,
5 / 4 8 / / / 4 / \ 7 2 1
Return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
Answer
1. Using the recursive solution, subtract the value of the current node for each recursion. Until the left and right child nodes of the node are empty.
Note: The value of sum is the root-to-leaf and must be to the leaf
2. Iterative method, BFS problem, using two queues to store node value and node's sum, when the left and right nodes of the current node are empty, and equal to the given value, returns true
The code is as follows:
/** * Definition for Binary tree * public class TreeNode {* int val, * TreeNode left, * TreeNode right; TreeNode (int x) {val = x;} *} */public class Solution {public Boolean haspathsum (TreeNode root, int sum) { if (Root==null) {return false; if (root.left==null&&root.right==null&&sum-root.val==0) {//note to have root node to leaf node path at the same time, only the root node is not compliant return true; } Boolean Bl=false; Boolean br=false; if (root.left!=null) {bl=haspathsum (root.left,sum-root.val); } if (Root.right!=null) {br=haspathsum (root.right,sum-root.val); } return bl| | Br }}//Iterative Method Public boolean haspathsum (TreeNode root,int sum) {if (Root==null) {return false; } queue<treenode> nodes=new linkedlist<treenode> (); Queue<integer> values=new linkedlist<integer> (); Nodes.Add (root); Values.add (Root.val); while (!nodes.isempty ()) {TreeNode Cur=nodes.poll (); int Sumval=values.poll (); if (cur.left==null&&cur.right==null&&sumval==sum) {return true; } if (Cur.left!=null) {Nodes.Add (cur.left); Values.add (Sumval+cur.left.val); } if (Cur.right!=null) {Nodes.Add (cur.right); Values.add (Sumval+cur.right.val); }} return false;}
---EOF---
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
"Leetcode" Path Sum