码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Sum Root to Leaf Numbers

时间:2014-09-11 23:40:42      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:des   blog   io   java   for   div   sp   log   on   

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

标签:des   blog   io   java   for   div   sp   log   on   

原文地址:http://www.cnblogs.com/yuhaos/p/3967414.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!