Coolde

ARTS1

2018-07-01

Algorithm

题目 112. Path Sum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

基本思路:

    1. 使用 DFS 遍历所有的叶节点,计算叶节点到根节点路径的节点 val 之和,等于给定数字则返回 true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
private boolean hasPath = false;
private int sum = 0;

public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
this.sum = sum;
this.dfs(root, 0);
return this.hasPath;
}

public void dfs(TreeNode node, int num) {
if (this.hasPath) {
return;
}
num += node.val;
if (node.left == null && node.right == null) {
if (num == this.sum){
this.hasPath = true;
}
}
if (node.left != null ){
this.dfs(node.left, num);
}

if (node.right != null ) {
this.dfs(node.right, num);
}

}
}

Review

日志的小短文 The Problem With Logging.

全文可以概括为: “No log everything”,”rules and regulations”

  • 日志打印过多,影响代码的可读性与可维护性
  • 消耗资源
  • 日志信息过多导致日后检索日志变得麻烦
  • 日志过多,但真正有用的信息很少

Tip

关于测试中的多线程与jvm相关场景思考:
https://cloudfeng.github.io/2018/06/29/arts/tip/T-java-thread-unit/

Share

Redis 数据持久化理解:
Redis 提供了两种方式: 快照与只追加文件。与 MySQL 的 dump 和 binlog 备份原理是基本一致。前者是将已经存储的数据导出进行备份,后者是根据对存储单元的修改操作进行备份。

使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏

扫描二维码,分享此文章