【树】Sum Root to Leaf Numbers

时间:2023-12-13 18:27:20

题目:

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
/ \
2 3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

思路:

利用栈进行深度优先遍历。

/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var sumNumbers = function(root) {
if(root==null){
return 0;
} function Node(treeNode,sum){
this.treeNode=treeNode;
this.sum=sum;
} var res=0,stack=[];
var n=new Node(root,root.val);
stack.push(n); while(stack.length!=0){
var p=stack.pop();
if(p.treeNode.left==null&&p.treeNode.right==null){
res+=p.sum;
}else{
if(p.treeNode.left!=null){
stack.push(new Node(p.treeNode.left,p.sum*10+p.treeNode.left.val))
}
if(p.treeNode.right!=null){
stack.push(new Node(p.treeNode.right,p.sum*10+p.treeNode.right.val))
}
}
} return res;
};