博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Sum Root to Leaf Numbers
阅读量:2194 次
发布时间:2019-05-02

本文共 1069 字,大约阅读时间需要 3 分钟。

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);    }};

转载于:https://my.oschina.net/vintnee/blog/640450

你可能感兴趣的文章
Linux下perf性能测试火焰图只显示函数地址不显示函数名的问题
查看>>
c结构体、c++结构体和c++类的区别以及错误纠正
查看>>
Linux下查看根目录各文件内存占用情况
查看>>
A星算法详解(个人认为最详细,最通俗易懂的一个版本)
查看>>
利用栈实现DFS
查看>>
逆序对的数量(递归+归并思想)
查看>>
数的范围(二分查找上下界)
查看>>
算法导论阅读顺序
查看>>
Windows程序设计:直线绘制
查看>>
linux之CentOS下文件解压方式
查看>>
Django字段的创建并连接MYSQL
查看>>
div标签布局的使用
查看>>
HTML中表格的使用
查看>>
(模板 重要)Tarjan算法解决LCA问题(PAT 1151 LCA in a Binary Tree)
查看>>
(PAT 1154) Vertex Coloring (图的广度优先遍历)
查看>>
(PAT 1115) Counting Nodes in a BST (二叉查找树-统计指定层元素个数)
查看>>
(PAT 1143) Lowest Common Ancestor (二叉查找树的LCA)
查看>>
(PAT 1061) Dating (字符串处理)
查看>>
(PAT 1118) Birds in Forest (并查集)
查看>>
数据结构 拓扑排序
查看>>