什么是流(Stream)?如何理解Nodejs中的
823 2023-04-03 05:11:14
原题传送门
1、思路分析
DFS,从根结点开始,遍历每个结点,如果遇到叶子结点,则将叶子结点对应的数字加到数字之和。如果当前不是叶子结点,则计算其子结点对应的数字,然后对子节点递归遍历。
2、代码实现
package Q0199.Q0129SumRoottoLeafNumbers;import DataStructure.TreeNode;// DFSpublic class Solution { public int sumNumbers(TreeNode root) { return sumAux(root, 0); } private int sumAux(TreeNode root, int res) { if (root == null) return 0; if (root.right == null && root.left == null) return res * 10 + root.val; return sumAux(root.left, res * 10 + root.val) + sumAux(root.right, res * 10 + root.val); }}
3、复杂度分析
时间复杂度: O(n)
空间复杂度: O(n)