Question: We define a root - to - node path to be any sequence of nodes in a tree starting with the root and proceeding downward
We define a "roottonode path" to be any sequence of nodes in a tree starting with the root and proceeding downward to a given node. The "roottonode path sum" for that path is the sum of the values for all the nodes including the root and the given node along that path. Define an empty tree to contain no roottonode paths and so its sum is zero Define a tree with one node equivalently the path to the root to have a roottonode path consisting of just the root and so its sum is the value of the root Given a binary tree and a value sum, return true if the tree has some roottonode path such that adding up all the values along the path equals sum. Return false if no such path exists.
Here are methods that you can use on the BinNode objects:
interface BinNode
public int value;
public void setValueint v;
public BinNode left;
public BinNode right;
public boolean isLeaf;
Your Answer:
public boolean hasPathSumBinNode root, int sum
if root null
return false;
if rootisLeaf
return root.value sum;
int remainingSum sum root.value;
return hasPathSumrootleft remainingSum hasPathSumrootright remainingSum;
public boolean BTpathsumBinNode root, int sum
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
