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;
    };
  • 相关阅读:
    java 日志体系
    java mail 接收邮件
    Spring 事物Transaction
    Spring 文件上传MultipartFile 执行流程分析
    centos7安装Elasticsearch7
    centos7安装docker笔记
    docker安装
    redis
    springboot+redis+nginx+分布式session
    tomcat程序和webapp分离
  • 原文地址:https://www.cnblogs.com/shytong/p/5166824.html
Copyright © 2011-2022 走看看