簡體   English   中英

給定節點的定義,計算二叉樹中節點的總和

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

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

實際上,這是一棵樹而不是二叉樹。 這是我的代碼

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

因此:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM