ð 129. æ±æ ¹èç¹å°å¶èç¹æ°åä¹å
2022幎10æ10æ¥
- algorithm
ð 129. æ±æ ¹èç¹å°å¶èç¹æ°åä¹å
éŸåºŠ: ð
é®é¢æè¿°
解æ³
/**
* 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 {
int res = 0;
public int sumNumbers(TreeNode root) {
// æè·¯ïŒ
// éåœ
mySol(root, 0);
return res;
}
private void mySol(TreeNode root, int preSum) {
// éåœç»æ¢æ¡ä»¶
int cur = root.val;
if(root.left == null && root.right == null) {
res += preSum * 10 + cur;
return;
}
if(root.left == null) {
// root.right != null
mySol(root.right, preSum * 10 + cur);
return;
}
if(root.right == null) {
mySol(root.left, preSum * 10 + cur);
return;
}
mySol(root.left, preSum * 10 + cur);
mySol(root.right, preSum * 10 + cur);
}
}