zoukankan      html  css  js  c++  java
  • 【树】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 a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {number}
     */
    var sumNumbers = function(root) {
        if(root==null){
            return 0;
        }
        
        function Node(treeNode,sum){
            this.treeNode=treeNode;
            this.sum=sum;
        }
        
        var res=0,stack=[];
        var n=new Node(root,root.val);
        stack.push(n);
        
        while(stack.length!=0){
            var p=stack.pop();
            if(p.treeNode.left==null&&p.treeNode.right==null){
                res+=p.sum;
            }else{
                if(p.treeNode.left!=null){
                    stack.push(new Node(p.treeNode.left,p.sum*10+p.treeNode.left.val))
                }
                if(p.treeNode.right!=null){
                    stack.push(new Node(p.treeNode.right,p.sum*10+p.treeNode.right.val))
                }
            }
        }
        
        return res;
    };
  • 相关阅读:
    @media screen响应式
    gulp轻松上手
    Node.js基本讲解
    百度地图
    SQL语言(增删改查)
    AJAX基本介绍(web前端)
    找出链表的第一个公共节点
    微软算法100题58 从尾到头输出链表(java)
    最长递增子序列
    各种排序算法
  • 原文地址:https://www.cnblogs.com/shytong/p/5166824.html
Copyright © 2011-2022 走看看