🌗 129. 求根节点到叶节点数字之和

吞䜛童子2022幎10月10日
  • algorithm
  • tree
小于 1 分钟

🌗 129. 求根节点到叶节点数字之和

隟床: 🌗

问题描述

img_41.png


解法

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

蟓出

img_40.png

䞊次猖蟑于: 2022/10/10 䞋午8:43:48
莡献者: liuxianzhishou