题目描述:
Find the sum of all left leaves in a given binary tree.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
思路一:
DFS迭代,利用Stack
对于一个给定的结点,判断它的左孩子是不是叶子结点,如果是,将它的值加到返回值上去,如果不是,加入stack。
判断它的右孩子是不是叶子结点,如果不是,加入stack。
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
int res = 0;
Stack<TreeNode> stack = new Stack<>();
stack.add(root);
while (!stack.isEmpty())
{
TreeNode node = stack.pop();
if (node.left != null)
{
if (node.left.left == null && node.left.right == null)
res += node.left.val;
else
stack.push(node.left);
}
if (node.right != null)
{
if (node.right.left != null || node.right.right != null)
stack.push(node.right);
}
}
return res;
}
}
思路二:DFS递归
对于一个给定的结点,判断其左孩子是不是叶子结点,如果是叶子结点,将值加到返回值上去,如果不是,递归调用。
递归调用其右孩子。
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
int res = 0;
if (root.left != null)
{
if (root.left.left == null && root.left.right == null)
res += root.left.val;
else
res += sumOfLeftLeaves(root.left);
}
res += sumOfLeftLeaves(root.right);
return res;
}
}
思路三:先序遍历,加flag判断是否为左孩子
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
return preorder(root, false);
}
public int preorder(TreeNode root, boolean left)
{
if (root == null)
return 0;
if (root.left == null && root.right == null && left)
return root.val;
return preorder(root.left, true) + preorder(root.right, false);
}
}
思路四:队列BFS
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
int res = 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty())
{
TreeNode node = queue.poll();
if (node.left != null && node.left.left == null && node.left.right == null)
res += node.left.val;
if (node.left != null)
queue.add(node.left);
if (node.right != null)
queue.add(node.right);
}
return res;
}
}