257. 二叉树的所有路径

tech2025-03-25  4

 简单题,做的心态很崩,不知道开始出现了什么错误,一直bug...................................怕不是一跃回到解放前了😭

import java.util.LinkedList; import java.util.List; class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }} class Solution { List<String> res = new LinkedList<>(); List<String> ress = new LinkedList<>(); private void dfs(TreeNode root, String s) { // 如果root为空,直接返回 if(root == null){ return; } // 如果不为空,计算应该插入的String String appStr = "->"+root.val; s += appStr; // 如果到了叶子节点 if(root.left == null && root.right == null){ res.add(s); s = s.substring(0, s.length() - appStr.length()); } if(root.left != null){ dfs(root.left, s); } if(root.right != null){ dfs(root.right, s); } } public List<String> binaryTreePaths(TreeNode root) { // 如果root为空,直接返回 if(root == null){ return res; } // 深搜 dfs(root, ""); for(String s1: res){ ress.add(s1.substring(2, s1.length())); System.out.println(s1); } return res; } public static void main(String[] args) { Solution s = new Solution(); TreeNode treeNode = new TreeNode(1); treeNode.left = new TreeNode(2); treeNode.right = new TreeNode(3); treeNode.left.left = new TreeNode(4); s.binaryTreePaths(treeNode); } }

 

最新回复(0)