java数据结构与算法刷题目录(剑指Offer、LeetCode、ACM)-----主目录-----持续更新(进不去说明我没写完):https://blog.csdn.net/grd_java/article/details/123063846 |
---|
- 深度优先遍历,或者广度优先
- 向下遍历时,如果是左边的结点,传输一个标志true
- 拿到结点后,如果是叶子结点,判断是否标志位时true,如果是,说明是左叶子
- 深度优先
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return sumOfLeftLeaves(root,false,0);
}
public int sumOfLeftLeaves(TreeNode root,boolean isLeft, int sumLeft){
if(root != null){
if(root.left == null && root.right == null){
sumLeft = isLeft?sumLeft+root.val:sumLeft;
}
sumLeft = sumOfLeftLeaves(root.left,true,sumLeft);
sumLeft = sumOfLeftLeaves(root.right,false,sumLeft);
}
return sumLeft;
}
}
写法二
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return root != null ? dfs(root) : 0;
}
public int dfs(TreeNode node) {
int ans = 0;
if (node.left != null) {
ans += isLeafNode(node.left) ? node.left.val : dfs(node.left);
}
if (node.right != null && !isLeafNode(node.right)) {
ans += dfs(node.right);
}
return ans;
}
public boolean isLeafNode(TreeNode node) {
return node.left == null && node.right == null;
}
}
- 广度优先
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
int ans = 0;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node.left != null) {
if (isLeafNode(node.left)) {
ans += node.left.val;
} else {
queue.offer(node.left);
}
}
if (node.right != null) {
if (!isLeafNode(node.right)) {
queue.offer(node.right);
}
}
}
return ans;
}
public boolean isLeafNode(TreeNode node) {
return node.left == null && node.right == null;
}
}