Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit a6b34c0

Browse files
committed
update.
1 parent 22cf8c1 commit a6b34c0

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

0404-左叶子之和.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# 左叶子之和
2+
3+
## 题目描述
4+
5+
计算给定二叉树的所有左叶子之和。
6+
7+
```
8+
3
9+
/ \
10+
9 20
11+
/ \
12+
15 7
13+
14+
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
15+
```
16+
17+
## 分析
18+
19+
使用递归的方法求解即可。
20+
21+
## 算法
22+
23+
```java
24+
/**
25+
* Definition for a binary tree node.
26+
* public class TreeNode {
27+
* int val;
28+
* TreeNode left;
29+
* TreeNode right;
30+
* TreeNode(int x) { val = x; }
31+
* }
32+
*/
33+
class Solution {
34+
public int sumOfLeftLeaves(TreeNode root) {
35+
return sumOfLeftLeaves(root, false);
36+
}
37+
38+
private int sumOfLeftLeaves(TreeNode root, boolean isLeft){
39+
if(root == null) return 0;
40+
if(root.left == null && root.right == null && isLeft)
41+
return root.val;
42+
return sumOfLeftLeaves(root.left, true) + sumOfLeftLeaves(root.right, false);
43+
}
44+
}
45+
```
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# 数字转换为十六进制数
2+
3+
## 题目描述
4+
5+
给定一个整数,编写一个算法将这个数转换为十六进制数。对于负整数,我们通常使用 补码运算 方法。
6+
7+
注意:
8+
9+
* 十六进制中所有字母(a-f)都必须是小写。
10+
* 十六进制字符串中不能包含多余的前导零。如果要转化的数为0,那么以单个字符'0'来表示;对于其他情况,十六进制字符串中的第一个字符将不会是0字符。
11+
* 给定的数确保在32位有符号整数范围内。
12+
* 不能使用任何由库提供的将数字直接转换或格式化为十六进制的方法。
13+
14+
## 分析
15+
16+
按位进行拼接即可。
17+
18+
## 算法
19+
20+
```java
21+
class Solution {
22+
public String toHex(int num) {
23+
if(num == 0) return "0";
24+
char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
25+
StringBuilder sb = new StringBuilder();
26+
while (sb.length() < 8 && num != 0) {
27+
sb.append(hex[num & 0xf]);
28+
num >>= 4;
29+
}
30+
return sb.reverse().toString();
31+
}
32+
}
33+
```

0 commit comments

Comments
 (0)