zoukankan      html  css  js  c++  java
  • 剑指 Offer II 049. 从根节点到叶节点的路径数字之和

    dfs水题

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
     * };
     */
    class Solution {
    public:
        int sum = 0;
        void dfs(TreeNode* root, int num)
        {
            num = num * 10 + root->val;
            if(root->left == nullptr && root->right == nullptr) 
            {
                sum += num;
                return;
            }
            if(root->left)
            {
                dfs(root->left, num);
            }
            if(root->right)
                dfs(root->right, num);
            num = (num - root->val) / 10;
        }
    
    
        int sumNumbers(TreeNode* root) {
            dfs(root, sum);
            return sum;
    
        }
    };
    自己选择的路,跪着也要走完。朋友们,虽然这个世界日益浮躁起来,只要能够为了当时纯粹的梦想和感动坚持努力下去,不管其它人怎么样,我们也能够保持自己的本色走下去。
  • 相关阅读:
    Puzzle, ACM/ICPC World Finals 1993, UVa227
    Puzzle, ACM/ICPC World Finals 1993, UVa227
    All in All, UVa 10340
    All in All, UVa 10340
    Box, ACM/ICPC NEERC 2004, UVa1587
    Box, ACM/ICPC NEERC 2004, UVa1587
    动态文本输出
    形态分析法
    粒子系统
    思维
  • 原文地址:https://www.cnblogs.com/WTSRUVF/p/15376863.html
Copyright © 2011-2022 走看看