my-leetcode-logs-20230610

Last updated on 2023年6月17日 下午

404.左叶子之和(迭代法)

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
34
35
36
37
38
39
40
41
42
43
44
/**
* 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 sumOfLeftLeaves(TreeNode root) {
//使用迭代法实现
int result = 0;
if(root == null){
return result;
}
Stack<TreeNode> st = new Stack<>();
st.push(root);
while(!st.isEmpty()){
TreeNode node = st.peek();
st.pop();
//判断下一个结点是不是左叶子结点
if(node.left != null && node.left.left == null && node.left.right == null){
result += node.left.val;
}

//按照右左中的顺序加入到stack中
if(node.left != null){
st.push(node.left);
}

if(node.right != null){
st.push(node.right);
}
}
return result;
}
}


my-leetcode-logs-20230610
https://thewangyang.github.io/2023/06/10/leetcode-notes-20230610/
Author
wyy
Posted on
2023年6月10日
Updated on
2023年6月17日
Licensed under