关于leetcode:leetcode树之从根到叶的二进制数之和

本文次要记录一下leetcode树之从根到叶的二进制数之和

题目

给出一棵二叉树,其上每个结点的值都是 0 或 1 。每一条从根到叶的门路都代表一个从最高无效位开始的二进制数。例如,如果门路为 0 -> 1 -> 1 -> 0 -> 1,那么它示意二进制数 01101,也就是 13 。

对树上的每一片叶子,咱们都要找出从根到该叶子的门路所示意的数字。

以 10^9 + 7 为模,返回这些数字之和。

 

示例:

![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/04/05/sum-of-root-to-leaf-binary-numbers.png)

输出:[1,0,1,0,1,0,1]
输入:22
解释:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

 

提醒:

    树中的结点数介于 1 和 1000 之间。
    node.val 为 0 或 1 。

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-root-to-leaf-binary-numbers
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

题解

/**
 * 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 {
    public int sumRootToLeaf(TreeNode root) {
        return sumNode(root, 0);
    }

    public int sumNode(TreeNode node, int sum) {
        if (node == null) {
            return 0;
        }

        sum = 2 * sum + node.val;

        if (node.left == null && node.right == null) {
            return sum;
        }

        return sumNode(node.left, sum) + sumNode(node.right, sum);
    }
}

小结

这里采纳递归的办法,当node为null时返回0;之后对sum累加以后node.val;若node.left及node.right为null则返回sum,否则递归计算sumNode(node.left, sum)再累加上sumNode(node.right, sum)。

doc

  • 从根到叶的二进制数之和

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理