代码随想录算法刷题训练营day18:LeetCode(257)二叉树的所有路径、LeetCode(404)左叶子之和
LeetCode(257)二叉树的所有路径
题目
代码
import java.util.ArrayList;
import java.util.List;/*** 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 List<String> binaryTreePaths(TreeNode root) {//递归+回溯--->获取二叉树的全部路径List<String> result=new ArrayList<>();//存放结果集合List<String> paths=new ArrayList<>();//存放临时路径集合//消除边缘情况if(root==null){return null;}//设置一个函数,用于递归+回溯所有路径的函数getPaths(result,paths,root);//它们均是引用型变量,是随着地址改变而改变return result; }public void getPaths(List<String> result,List<String> paths,TreeNode root){//遍历路径时,需采用前序遍历//首先应把路径加入进去,防止再判断终止条件时空指针异常paths.add(String.valueOf(root.val));//终止条件----到叶子节点if(root.left==null&&root.right==null){//终止条件的时候,需要把路径返回到result结果中StringBuilder sb=new StringBuilder();for (int i = 0; i < paths.size(); i++) {sb.append(paths.get(i));if(i!=paths.size()-1){sb.append("->");}}String path=sb.toString();result.add(path);}//遍历左子树----当成根节点if(root.left!=null){//左子树不为空的时候进行遍历getPaths(result, paths,root.left);//回溯---剪支paths.remove(paths.size()-1);//把最后一个元素,也就是刚刚遍历到的下一个元素给干掉}if (root.right!=null) {getPaths(result, paths, root.right);paths.remove(paths.size()-1); }}}
LeetCode(404)左叶子之和
题目
代码
/*** 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 sum=0;//递归条件变化一下if(root==null){return 0;}if(root.left==null&&root.right==null){return 0;}//int sum=0;int result=sumOfLeftLeavesTest(root);return result;}public int sumOfLeftLeavesTest(TreeNode root){if(root==null){return 0;}if(root.left==null&&root.right==null){return 0;}int leftSum=sumOfLeftLeavesTest(root.left);//此时是左子树,同样也是叶子节点int rightSum=sumOfLeftLeavesTest(root.right);int leftValue=0;if(root.left!=null&&root.left.left==null&&root.left.right==null){//空指针异常问题leftValue=root.left.val;}int sum=leftSum+rightSum+leftValue;return sum;}
}