给定节点的定义,计算二叉树中节点的总和

given a definition of node, calculate the sum of the nodes in binary tree

class Node{ 
  int value; 
  List<Node> childNodes;
}

上面是Node的定义,不知道二叉树的求和如何实现

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;
}

实际上,这是一棵树而不是二叉树。这是我的代码

树中节点的总和为:节点的值+左树的总和+右树的总和。

因此:

public static int sum(TreeNode node) {
    if(node == null) {
        return 0;
    } else {
        return node.getVal() + sum(node.getLeft()) + sum(node.getRight());
    }
}
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;
}