Get the sum of all node values of the tree (N-ary tree)

Ideas

The solution to this problem is similar to that of a standard binary tree. It traverses the entire linked list and continuously accumulates values, which can be achieved by using layer order traversal or recursion.

Code

int findSum(TreeNode root){
    
    
  if(root == null)
    return 0;
  return root.getData()+findSum(root.getFirstChild())+findSum(root.getNextSibling());
}

Guess you like

Origin blog.csdn.net/weixin_37632716/article/details/114988498