首页 > 代码库 > [LeetCode] Sum Root to Leaf Numbers
[LeetCode] Sum Root to Leaf Numbers
public class Solution { public int sumNumbers(TreeNode root) { int sum=0; TreeNode nowNode = root; Stack<TreeNode> nodeStack = new Stack<TreeNode>(); boolean popNode = false; while (!(nowNode==root && popNode)) { if (!popNode) { if (nowNode != null) { nodeStack.push(nowNode); nowNode = nowNode.left; } else { popNode = true; } } else { TreeNode topNode = nodeStack.peek(); if (nowNode == topNode.right) { if (topNode.left==null && topNode.right==null) { sum = sum + getNumber(nodeStack); } nowNode = nodeStack.pop(); } else { nowNode = topNode.right; popNode = false; } } } return sum; } public int getNumber(Stack<TreeNode> nodeStack) { int num = 0; for (Iterator<TreeNode> itor=nodeStack.iterator(); itor.hasNext();) { num = num*10 + itor.next().val; } return num; }}
[LeetCode] Sum Root to Leaf Numbers
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。