【树】Sum Root to Leaf Numbers
2016-01-28 16:45
375 查看
题目:
Given a binary tree containing digits from
An example is the root-to-leaf path
Find the total sum of all root-to-leaf numbers.
For example,
The root-to-leaf path
The root-to-leaf path
Return the sum = 12 + 13 =
思路:
利用栈进行深度优先遍历。
Given a binary tree containing digits from
0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path
1->2->3which 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->2represents the number
12.
The root-to-leaf path
1->3represents 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; };
相关文章推荐
- the fourth class
- iOS UINavigationController
- WPF容器控件
- 摄像头的像素如何计算
- re 模块错误 error: bad character range
- MD5
- 无法自动生成R.java中的内部类代码
- JAVA获取json中的全部键值对
- 什么是C语言局部程序块(local block)
- 一位毕业生的肺腑之言: 大学生活应该怎样度过——写给学弟学妹
- Android中使用GSON包解析JSON数据(简单JSON)
- React Native 配置遇到的错误:TransformError
- linux e2fsprogs安装解决uuid/uuid.h: No such file or directory错误
- Redis缓存相关
- 初识java 多线程
- 三分钟了解mongodb
- debian下安装Theano(附pydot问题解决方法)
- centos 安装ffmpeg x264版
- IE 浏览器安全级别详情及区别小结
- Angular实现form自动布局