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

      

  • 相关阅读:
    前端调用后台接口下载word文档的两种方法
    Layui form表单提交注意事项
    JavaScript_Util_01
    心理
    小例子
    SQL分割字符串
    绘制10种不同颜色的散点图
    绘制散点图
    subplot的使用
    绘制正弦余弦
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3766844.html
Copyright © 2020-2023  润新知