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.

    针对每一个结点, 都把它当作叶子来处理, 这样, 每个结点都会有个值, 其值的大小是父结点的值*10, 返回值就加上自己的结点

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int vers(TreeNode *root, int path)
        {
            if(NULL==root)return 0;
            if(NULL==root->left&&NULL==root->right)
                return path * 10 + root->val;
            return vers(root->left, path * 10 + root->val) + vers(root->right, path * 10 + root->val);
        }
        int sumNumbers(TreeNode *root)
        {
            int path = 0;
            return vers(root, path);
        }
    };


    每天早上叫醒你的不是闹钟,而是心中的梦~
  • 相关阅读:
    run blackberry Sim&MDS4.7
    jsadd input name
    java memory
    silverlight Pivot Hearder
    eclipse tomcat server
    Monitor.Wait初探(5)
    Monitor.Wait初探(4)
    Monitor.Wait初探(2)
    解决远程注册表打不开,Cannot open HKEY_LOCAL_MACHIN…
    Windows界面自动化技术发展概要(二)
  • 原文地址:https://www.cnblogs.com/vintion/p/4116930.html
Copyright © 2011-2022 走看看