输出二叉树所有路径,java

package main.java;/*
* @Description: 遍历所有的树
* @Author: du_zj
* @Date: 2022/3/22.
*/

import java.util.ArrayList;
import java.util.List;

public class ListTree {


public boolean hasPathSum(TreeNode root, int sum) {
List<Integer> list = new ArrayList<>();
dfs(root, list);
List<String> strings = new ArrayList<>();
helper(root, root.val + "", strings);
System.out.println(strings);
return true;
}

public void helper(TreeNode root, String path, List<String> result) {
if (root == null) {
return;
}

if (root.left == null && root.right == null) {
result.add(path);
return;
}

if (root.left != null) {
helper(root.left, path + "->" + root.left.val, result);
}

if (root.right != null) {
helper(root.right, path + "->" + root.right.val, result);
}
}



List<List<Integer>> results = new ArrayList<>();
public boolean hasPathSum2(TreeNode root, int sum) {
List<Integer> list = new ArrayList<>();
dfs(root, list);
System.out.println(results.toString());
return true;
}



private void dfs(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
results.add(list);
}
list.add(root.val);
if (root.left != null) {
dfs(root.left, new ArrayList<>(list));
}
if (root.right != null) {
dfs(root.right, new ArrayList<>(list));
}
}

static class TreeNode{
TreeNode left;
TreeNode right;
Integer val;

}
public static void main(String[] args) {
TreeNode root1 = new TreeNode();
TreeNode root2 = new TreeNode();
TreeNode root3 = new TreeNode();
TreeNode root4 = new TreeNode();
TreeNode root5 = new TreeNode();
root1.val = 10;
root2.left = root1;
root3.val = 8;
root2.right = root3;
root2.val = 6;
root4.left = root2;
root4.val = 2;
root5.val = 0;
root4.right = root5;
int sum = 0;
ListTree nv = new ListTree();
nv.hasPathSum(root4,sum);
}
}
posted @ 2022-03-22 10:01  多语种程序员  阅读(121)  评论(0编辑  收藏  举报