输出树的所有路径

1.问题描述

给一棵二叉树,找出从根节点到叶子节点的所有路径。

2.解法

找出所有路径这种问题,一般都是dfs+递归的方法解决即可。
对于二叉树来说,递归的核心在于不断dfs到树的叶子节点,然后再回溯回去。在递归函数中,当遇到叶子节点,即该节点即无左子树又无右子树的时候,就是一条完整的路径。

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

/**
 * Created by wanglei on 19/4/14.
 */
public class FindAllPath {

    public static TreeNode<Integer> init() {
        TreeNode<Integer> root = new TreeNode<>(1);
        TreeNode<Integer> node2 = new TreeNode<>(2);
        TreeNode<Integer> node3 = new TreeNode<>(3);
        TreeNode<Integer> node5 = new TreeNode<>(5);
        root.left = node2;
        root.right = node3;
        node2.right = node5;
        return root;
    }

    public static void helper(TreeNode<Integer> 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.data.toString(), result);
        }

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

    public static List<String> slove(TreeNode<Integer> root) {
        List<String> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        helper(root, root.data.toString(), result);
        return result;
    }

    public static void printArray(List<String> list) {
        for(String ele: list) {
            System.out.println(ele);
        }
    }

    public static void main(String[] args) {
        TreeNode<Integer> root = init();
        List<String> result = slove(root);
        printArray(result);
    }

}
发布了425 篇原创文章 · 获赞 1607 · 访问量 436万+

猜你喜欢

转载自blog.csdn.net/bitcarmanlee/article/details/89299623