zoukankan      html  css  js  c++  java
  • Sum Root to Leaf Numbers

    问题:根节点到叶子结点的所有权值和
    分析:从根节点遍历,若遍历到叶子结点,则sum+其路径的所有权值和

    /**
     * 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 sum;
        void dfs(TreeNode *root,int num)
        {
            if(root->left==NULL && root->right==NULL) sum+=num;
            if(root->left) dfs(root->left,num*10+root->left->val);
            if(root->right) dfs(root->right,num*10+root->right->val);
        }
        int sumNumbers(TreeNode *root) {
            if(root==NULL) return 0;
            sum=0;
            int num=0;
            dfs(root,root->val);
            return sum;
        }
    };
    

      

  • 相关阅读:
    Cyclic Nacklace HDU
    Oulipo HDU
    Period HDU
    Blue Jeans POJ
    剪花布条 HDU
    最长公共前缀 CSU
    Clock Pictures CSU
    Number Sequence HDU
    Arrange the Bulls POJ
    Traveling by Stagecoach POJ
  • 原文地址:https://www.cnblogs.com/zsboy/p/3895302.html
Copyright © 2011-2022 走看看