404:左叶子之和
404:左叶子之和
计算给定二叉树的所有左叶子之和。
示例:
思路
递归法
递归的遍历顺序为后序遍历(左右中),是因为要通过递归函数的返回值来累加求取左叶子数值之和。
中间结点逻辑的处理
如果该节点的左节点不为空,该节点的左节点的左节点为空,该节点的左节点的右节点为空,则找到了一个左叶子
当遇到左叶子节点的时候,记录数值,然后通过递归求取左子树左叶子之和,和 右子树左叶子之和,相加便是整个树的左叶子之和。
迭代法
判断条件同递归
代码
//递归 后续遍历实现
public static int leftTreeSum2(Node root) {
if (root == null) return 0;
Stack<Node> stack = new Stack<>();
int result = 0;
stack.push(root);
while (!stack.isEmpty()) {//中
Node temp = stack.pop();
if (temp.left != null && temp.left.left == null && temp.left.right == null) {
result += temp.left.val;
}
if (temp.right != null) stack.push(temp.right);//右
if (temp.left != null) stack.push(temp.left);//左
}
return result;
}
//迭代 后续遍历实现
public static int leftTreeSumR2(Node root) {
if (root == null) return 0;
Stack<Node> stack = new Stack<>();
stack.push(root);
int sum = 0;
while (!stack.isEmpty()) {
Node temp = stack.pop();
if (temp.left != null && temp.left.left == null && temp.left.right == null) {
sum+=temp.left.val;
}
if(temp.right!=null){
stack.push(temp.right);
}
if(temp.left!=null){
stack.push(temp.left);
}
}
return sum;
}