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;     
        }
    }
    

      

  • 相关阅读:
    一段路
    memcache 键名的命名规则以及和memcached的区别
    浏览器解释网页时乱码
    windows下安装Apache
    巧用PHP数组函数
    程序返回值的数据结构
    Linux如何生成列表
    判断用户密码是否在警告期内(学习练习)
    判断用户的用户名和其基本组的组名是否一致
    sed笔记
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3766844.html
Copyright © 2011-2022 走看看