欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++实现LeetCode(129.求根到叶节点数字之和)

程序员文章站 2022-03-11 08:18:22
[leetcode] 129. sum root to leaf numbers 求根到叶节点数字之和given a binary tree containing digits from 0...

[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.

note: a leaf is a node with no children.

example:

input: [1,2,3]
1
/ \
2   3
output: 25
explanation:
the root-to-leaf path

1->2

represents the number

12

.
the root-to-leaf path

1->3

represents the number

13

.
therefore, sum = 12 + 13 =

25

.

example 2:

input: [4,9,0,5,1]
4
/ \
9   0
/ \
5   1
output: 1026
explanation:
the root-to-leaf path

4->9->5

represents the number 495.
the root-to-leaf path

4->9->1

represents the number 491.
the root-to-leaf path

4->0

represents the number 40.
therefore, sum = 495 + 491 + 40 =

1026

.

这道求根到叶节点数字之和的题跟之前的求 path sum 很类似,都是利用dfs递归来解,这道题由于不是单纯的把各个节点的数字相加,而是每遇到一个新的子结点的数字,要把父结点的数字扩大10倍之后再相加。如果遍历到叶结点了,就将当前的累加结果sum返回。如果不是,则对其左右子结点分别调用递归函数,将两个结果相加返回即可,参见代码如下:

解法一:

class solution {
public:
    int sumnumbers(treenode* root) {
        return sumnumbersdfs(root, 0);
    }
    int sumnumbersdfs(treenode* root, int sum) {
        if (!root) return 0;
        sum = sum * 10 + root->val;
        if (!root->left && !root->right) return sum;
        return sumnumbersdfs(root->left, sum) + sumnumbersdfs(root->right, sum);
    }
};

我们也可以采用迭代的写法,这里用的是先序遍历的迭代写法,使用栈来辅助遍历,首先将根结点压入栈,然后进行while循环,取出栈顶元素,如果是叶结点,那么将其值加入结果res。如果其右子结点存在,那么其结点值加上当前结点值的10倍,再将右子结点压入栈。同理,若左子结点存在,那么其结点值加上当前结点值的10倍,再将左子结点压入栈,是不是跟之前的 path sum 极其类似呢,参见代码如下:

解法二:

class solution {
public:
    int sumnumbers(treenode* root) {
        if (!root) return 0;
        int res = 0;
        stack<treenode*> st{{root}};
        while (!st.empty()) {
            treenode *t = st.top(); st.pop();
            if (!t->left && !t->right) {
                res += t->val;
            }
            if (t->right) {
                t->right->val += t->val * 10;
                st.push(t->right);
            }
            if (t->left) {
                t->left->val += t->val * 10;
                st.push(t->left);
            }
        }
        return res;
    }
};

github 同步地址:

类似题目:

path sum

binary tree maximum path sum

参考资料:

https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/41367/non-recursive-preorder-traverse-java-solution

https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/41452/iterative-c%2b%2b-solution-using-stack-(similar-to-postorder-traversal)

到此这篇关于c++实现leetcode(129.求根到叶节点数字之和)的文章就介绍到这了,更多相关c++实现求根到叶节点数字之和内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!