您的位置:首页 > 其它

【树】Sum Root to Leaf Numbers

2016-01-28 16:45 375 查看
题目:

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;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: