你好 我正在嘗試實現 hasPathSum()
對於給定數字的意思是在根到葉節點之間存在任何路徑。
我從斯坦福網站上獲得了這段代碼。我認為這是錯誤的
/**
Given a tree and a sum, returns true if there is a path from the root
down to a leaf, such that adding up all the values along the path
equals the given sum.
Strategy: subtract the node value from the sum when recurring down,
and check to see if the sum is 0 when you run out of tree.
*/
boolean hasPathSum(Node node, int sum) {
//return true if we run out of tree and sum==0
if (node == null){
return(sum == 0);
}
else {
//otherwise check both subtrees
int subSum = sum - node.data;
return(hasPathSum(node.left, subSum) || hasPathSum(node.right, subSum));
}
這是正確的實施嗎?
我想這如果應該是
- if(node.left==null && node.right==null)
如果我錯了請清除我的困惑
考慮這種情況:
5
/\
2 1
/
3
-謝謝