2015-12-20 50 views
0
class Node{ 
    int value; 
    List<Node> childNodes; 
} 

以上是節點的定義,我不知道如何實現二叉樹的總和。給出節點的定義,計算二叉樹中節點的總和

public class TreeNode { 
    int val; 
    TreeNode left; 
    TreeNode right; 

    TreeNode(int x) { 
    val = x; 
    } 
} 

但是,我可以理解這個版本的節點,二叉樹的節點之和可以通過遞歸實現。


public static int sumTree(Node root) { 
    int sum = 0; 
    if (root == null) { 
     return 0; 
    } 
    // Line 1 
    for (int i = 0; i < root.childNodes.size(); i++) { 
     sum = sum + root.childNodes.get(i).value + sumTree(root.childNodes.get(i)); 
    } 
    return sum; 
} 

其實,這是一棵樹,而不是二進制樹。這是我的代碼

+0

你嘗試自己什麼?告訴我們你自己試過的代碼。 – YoungHobbit

+0

我仍在嘗試,並且有很多錯誤,我會盡快發佈我的代碼。 – sevenxuguang

回答

0
public int sum(Node root) { 
    if (root == null) { 
     return 0; 
    } else if (root.childNodes == null) { 
     return root.value; 
    } 

    int sum = root.value; 
    for (Node child : root.childNodes) { 
     sum += sum(child); 
    } 
    return sum; 
} 
1

樹中節點的總和爲:節點+左樹總和+右樹總和的值。

因此:

public static int sum(TreeNode node) { 
    if(node == null) { 
     return 0; 
    } else { 
     return node.getVal() + sum(node.getLeft()) + sum(node.getRight()); 
    } 
} 
+0

是的,這是基於Node的第二個定義,第一個(子節點列表的節點)怎麼樣? – sevenxuguang