1
質問です:バイナリツリーの最大合計のパスのためのソリューションでのエラーを探す
最大パス和を見つけ、バイナリツリーを考えます。
パスは、ツリー内の任意のノードで開始とエンドとすることができます。
例:バイナリツリーを考える
:
1
/\
2 3
戻る6.
私の最初の解決策だった:LeetCodeに92分の90のテストケースを合格
public class Solution {
int max = Integer.MIN_VALUE;//This is to handle the scenario where the value of all nodes is negative
public int maxPathSum(TreeNode a) {
if(a == null){
return 0;
}
int sum = maxSum(a);
return max > sum ? max : sum;
}
public int maxSum(TreeNode node){
if(node == null){
return 0;
}
//handling the scenario where sum of any path is not greater than the value of single node
if(node.val > max){
max = node.val;
}
int leftChildSum = maxSum(node.left);
//path from current node to left child is maximum
if(node.val + leftChildSum > max){
max = node.val + leftChildSum;
}
int rightChildSum = maxSum(node.right);
//path from current node to right child is maximum
if(node.val + rightChildSum > max){
max = node.val + rightChildSum;
}
////path from left child to right child via current node is maximum
if(node.val + leftChildSum + rightChildSum > max){
max = node.val + leftChildSum + rightChildSum;
}
return Math.max(node.val + leftChildSum, node.val + rightChildSum);
}
}
しかし、私はこの解決策はm odified。
ノードが正の値を持ち、leftChildSum
とrightChildSum
の両方が負の値であるシナリオを考えてみましょう。この場合、ノードの値が返されます。ソリューションを修正
:LeetCode
public class Solution {
int max = Integer.MIN_VALUE;//This is to handle the scenario where the value of all nodes is negative
public int maxPathSum(TreeNode a) {
if(a == null){
return 0;
}
int sum = maxSum(a);
return max > sum ? max : sum;
}
public int maxSum(TreeNode node){
if(node == null){
return 0;
}
//handling the scenario where sum of any path is not greater than the value of single node
if(node.val > max){
max = node.val;
}
int leftChildSum = maxSum(node.left);
//path from current node to left child is maximum
if(node.val + leftChildSum > max){
max = node.val + leftChildSum;
}
int rightChildSum = maxSum(node.right);
//path from current node to right child is maximum
if(node.val + rightChildSum > max){
max = node.val + rightChildSum;
}
////path from left child to right child via current node is maximum
if(node.val + leftChildSum + rightChildSum > max){
max = node.val + leftChildSum + rightChildSum;
}
//Changes are below
int temp = node.val;
int value = Math.max(temp, node.val + leftChildSum);
value = Math.max(temp, node.val + rightChildSum);
return value;
}
}
に92分の63のテストケースを合格誰かが私の修正溶液でいただきました!間違っを把握助けてくださいことはできますか?
これはcodereviewに属している必要がありますか? – Moira
@ 1blustone nope。コードが意図したとおりに動作しない、OPはバグがどこにあるかを理解するのに助けを求めている。それは[codereview.se]のトピックではありません。 –