🟡 剑指 Offer II 049. 从根节点到叶节点的路径数字之和
LeetCode 提示
题目难度 中等
原题链接 🔗 leetcode
#
题解1就遍历
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */class Solution { private int res = 0;
private void dfs(int parent, TreeNode node) { if (node == null) { return; }
int nxtPrt = parent * 10 + node.val;
if (node.left == null && node.right == null) { res += nxtPrt; return; }
if (node.left != null) { dfs(nxtPrt, node.left); }
if (node.right != null) { dfs(nxtPrt, node.right); } }
public int sumNumbers(TreeNode root) { dfs(0, root);
return res; }}