力扣算法
257. 二叉树的所有路径
404. 左叶子之和
具体内容
257. 二叉树的所有路径
给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [1,2,3,null,5] 输出:[“1->2->5”,“1->3”]
示例 2:
输入:root = [1] 输出:[“1”]
提示:
树中节点的数目在范围 [1, 100] 内
-100 <= Node.val <= 100
做题思路
通过递归以及前序遍历的方式,依次从根节点遍历到叶子节点
解题
递归
class Solution {
//递归 前序遍历
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
if(root == null){
return result;
}
List<Integer> list = new ArrayList<>();
traversal(root,list,result);
return result;
}
//list1表遍历的路径,list2表最后返回的结果
public void traversal(TreeNode node,List<Integer> list1,List<String> list2){
//中 先添加节点的值,不然在下面判断条件中,若是节点的左右为空,则无法添加节点值
list1.add(node.val);
if(node.left == null && node.right == null){
//注意这里要返回题目要求的结构
StringBuilder st = new StringBuilder();
for(int i = 0;i < list1.size();i++){
st.append(list1.get(i));
if(i != list1.size()-1){
st.append("->");
}
}
list2.add(st.toString());
return;
}
//递归其实就是调用方法执行单层逻辑的代码,可通过这一性质更好的写出递归
//左
if(node.left!=null){
traversal(node.left,list1,list2);
list1.remove(list1.size()-1);
}
//右
if(node.right != null){
traversal(node.right,list1,list2);
list1.remove(list1.size()-1);
}
}
}
404. 左叶子之和
给定二叉树的根节点 root ,返回所有左叶子之和。
示例 1:
输入: root = [3,9,20,null,null,15,7] 输出: 24 解释: 在这个二叉树中,有两个左叶子,分别是 9 和
15,所以返回 24
示例 2:
输入: root = [1] 输出: 0
提示:
节点数在 [1, 1000] 范围内
-1000 <= Node.val <= 1000
做题思路
重点放在判断是否是叶子节点以及左叶子是否为空的条件上,递归顺序用后序遍历,从后往前遍历,再返回总的数目
解题
递归
//题目是左叶子 因此是左右叶子都没节点的
class Solution {
public int sumOfLeftLeaves(TreeNode root){
if(root == null){
return 0;
}
//左
int leftNum = sumOfLeftLeaves(root.left);
//右
int rightNum = sumOfLeftLeaves(root.right);
//中
int midValue = 0;
if (root.left != null && root.left.left == null && root.left.right == null) {
midValue = root.left.val;
}
int sum = midValue + leftValue + rightValue; // 中
return sum;
}
}
迭代
由于涉及到回溯的过程,因此用栈的数据结构
class Solution {
public int sumOfLeftLeaves(TreeNode root){
if (root == null) return 0;
Stack<TreeNode> stack = new Stack<> ();
stack.add(root);
int result = 0;
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
if (node.left != null && node.left.left == null && node.left.right == null) {
result += node.left.val;
}
if (node.right != null) stack.add(node.right);
if (node.left != null) stack.add(node.left);
}
return result;
}
}