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

      

  • 相关阅读:
    js --- for in 和 for of
    vue -- config index.js 配置文件详解
    vue -- 脚手架之webpack.dev.conf.js
    vue --- 解读vue的中webpack.base.config.js
    vue 引入第三方字体包
    js call 和 apply
    vue2.0中的$router 和 $route的区别
    懒加载js实现和优化
    vue的指令在webstrom下报错
    BFC的布局规则和触发条件
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3766844.html
Copyright © 2011-2022 走看看