前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 1022 Sum of Root To Leaf Binary Numbers

LeetCode 1022 Sum of Root To Leaf Binary Numbers

作者头像
一份执着✘
发布2019-12-30 17:00:23
2970
发布2019-12-30 17:00:23
举报
文章被收录于专栏:赵俊的Java专栏赵俊的Java专栏

题意

给予一颗二叉树,每个节点的值只有 0 和 1, 每个根到叶子节点的路径都是一个有效的二进制树, 如: 0 -> 1 -> 1 -> 0 -> 1, 那么用二进制表示就是 01101, 对应十进制为 13.

对于树中的所有叶子节点, 请返回根节点到这些叶子节点的路径所代表的二进制值的和.

例 :

代码语言:javascript
复制
给予树:

     1
   /   \
  0     1
 / \   / \
0   1 0   1

返回: 22. 
说明:  (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

解法

采用深度优先遍历, 从跟节点开始, 到下一层的时候, 将父节点的值向左移动一位, 再加上当前节点的值, 直到根节点为止.

如上图中, 1 -> 0 -> 0 这个路径, 从根节点 1 开始, 到第二层, 对 1 左移一位 i = 1 << 1, 等于 10, 再加上当前节点的值 0 等于 10, 再到下一层, 向左移动一位 i = 10 << 1, 等于 100.

代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    int result = 0;
    
    public int sumRootToLeaf(TreeNode root) {
        dfs(root, 0);
        return result;
    }
    
    public void dfs(TreeNode node, int currentVal) {
        if (node != null) {
            currentVal <<= 1;
            currentVal += node.val;
            if (node.left == null && node.right == null) {
                result += currentVal;
            }
            dfs(node.left, currentVal);
            dfs(node.right, currentVal);
        }
    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Sum of Root To Leaf Binary Numbers. Memory Usage: 35.4 MB, less than 100.00% of Java online submissions for Sum of Root To Leaf Binary Numbers.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-05-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题意
  • 解法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档