zoukankan      html  css  js  c++  java
  • leetcode--Sum Root to Leaf Numbers

    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 binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        /**This problem is just an implementation of bfs<br>
         *The algorithm is straightforward:<br>
         * @author Averill Zheng
         * @version 2014-06-02
         * @since JDK 1.7
         */
        public int sumNumbers(TreeNode root) {
            int sum = 0;
            Queue<TreeNode> node = new LinkedList<TreeNode>();
            Queue<Integer> number = new LinkedList<Integer>();
            if(root != null){
            	node.add(root);
            	number.add(root.val);
            	while(node.peek() != null){
            		TreeNode aNode = node.poll();
            		int num = number.poll();
            		if(aNode.left != null){
            			node.add(aNode.left);
            			number.add(num * 10 +aNode.left.val);
            		}
            		if(aNode.right != null){
            			node.add(aNode.right);
            			number.add(num * 10 +aNode.right.val);
            		}
            		if(aNode.left == null && aNode.right == null){
            			sum += num;
            		}
            	}
            }
            return sum;     
        }
    }
    

      

  • 相关阅读:
    cscope的使用
    关于函数指针
    linux内核源码目录(转)
    lcc之内存分配
    符号管理之符号表
    监听UITextFiled文本发生改变
    Debugging Tools for Windows__from WDK7
    WinDBG__独立安装文件
    20160215
    QT Creator 代码自动补全
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3766844.html
Copyright © 2011-2022 走看看