2017-02-23 5 views
-3

バイナリツリーが与えられた場合、パスの数(葉で終わる)を見つける必要があります。パスは渡された数に等しい。パス内の要素の合計が渡された数と等しいパスの数を見つける(葉で終わる)

私のコードに誤りがあります。

など。ツリーはであり、数が渡された場合、我々は、2つのパスを持っているよりも22

ある10->> 7 5-および10-> 12合計はしたがって22である場合、答えは2であります。

例ツリーはであり、渡された数は、我々は唯一のパスを持っているよりも22

ある場合10- 12として> 5>図7は、リーフノードと1又は3に増加する追加ありません22.上記値はだから、答えは1

// Javaプログラムが //与えられた数

/*バイナリツリーのノードがデータを有し、ポインタに等しい葉路和に印刷ルートに印刷します左の子に と右の子へのポインタ*/

class Node 
{ 
    int data; 
    Node left, right; 

    Node(int item) 
    { 
     data = item; 
     left = right = null; 
    } 
} 

class BinaryTree { 
int count =0; 
    Node root; 

    /* 
    Given a tree and a sum, return 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. 
    */ 

    int haspathSum(Node node, int sum) 
    { 
     if (node == null) 
     { 
      return (count=0); 
     } 
     else 
     { 

      /* otherwise check both subtrees */ 
      int subsum = sum - node.data; 

      if (subsum == 0 && node.left == null && node.right == null) 
        count = count + 1; 
        //return count; 
     if node.left 
       haspathSum(node.left, subsum); 
       //return count; 
      if (node.right) 
       haspathSum(node.right, subsum); 

      return count; 

     } 

    } 


    /* Driver program to test the above functions */ 
    public static void main(String args[]) 
    { 
     int sum = 22; 

     /* Constructed binary tree is 
      10 
      /\ 
     8 2 
     /\/
     3 5 2 
     */ 
     BinaryTree tree = new BinaryTree(); 
     tree.root = new Node(10); 
     tree.root.left = new Node(5); 
     tree.root.right = new Node(12); 
     tree.root.left.left = new Node(4); 
     tree.root.left.right = new Node(7); 
     //tree.root.right.left = new Node(2); 

// BinaryTree ch = new BinaryTree(); 
      System.out.println("count = " +tree.haspathSum(tree.root,sum)); 
    }  

} 

エラー: -

46: error: incompatible types: Node cannot be converted to boolean 
     if (node.left) 
       ^
49: error: incompatible types: Node cannot be converted to boolean 
      if (node.right) 
        ^
2 errors 
+3

エラーはかなり明確です。 'if(node.left!= null)'を意味しますか? – khelwood

+0

愚かなエラーを教えていただきありがとうございます。 – user6313669

答えて

2

エラーメッセージは、ブールが予想されたNode型の値を使用していることを語っています。 CとJavaScriptのような他の言語ではnullの場合は自動的にfalseと評価されます。の式はJavaでは表示されません。

if (node.left != null)と書いて、node.rightと同じとしたいと思います。

関連する問題