zoukankan      html  css  js  c++  java
  • LeetCode(129) 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,
    题目
    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.

    分析

    按照二叉树的深度遍历,累计所有路径组成整数的和。

    使用二叉树的递归深度优先遍历实现!

    AC代码

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int sumNumbers(TreeNode* root) {
            int ret = 0;
            if (!root)
                return ret;
            else if (!root->left && !root->right)
            {
                ret = root->val;
                return ret;
            }
            else
                dfs(root, root->val , ret);
    
            return ret;
        }
    
        //深度优先遍历,得到所有根节点到叶子节点的路径和
        void dfs(TreeNode *root, int val, int &sum)
        {
            if (!root->left && !root->right)
                sum += val;
            if (root->left)
            {
                dfs(root->left, val * 10 + root->left->val, sum);
            }
    
            if (root->right)
            {
                dfs(root->right, val * 10 + root->right->val, sum);
            }
        }
    };

    GitHub测试程序源码

  • 相关阅读:
    归并排序算法
    交换排序算法
    插入排序算法
    DASCTF2021五月赛
    第二届newsctf
    山西省赛
    2021广东省第一届网络安全竞赛
    2021 DozerCTF
    2021-HSCTF re
    buuctf-re (持续更新)
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214767.html
Copyright © 2011-2022 走看看