二叉搜索树路径列表 [英] binary search tree path list

查看:29
本文介绍了二叉搜索树路径列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是获取二叉树中所有根到叶路径的代码,但它将所有路径连接成一个路径.递归调用出了什么问题?

This is code to get all the root to leaf paths in a Binary Tree but it puts in all the paths concatenated into one path. What is going wrong with the recursive call?

private void rec(TreeNode root,List<Integer> l, List<List<Integer>> lists) {
    if (root == null) return;

    if (root.left == null && root.right == null ) {
        l.add(root.val);
        lists.add(l);
    }

    if (root.left != null) {
        l.add(root.val);
        rec(root.left,l,lists);

    }
    if (root.right != null) {
        l.add(root.val);
        rec(root.right,l,lists);

    }

}

推荐答案

您正在为所有路径重复使用相同的 l 列表,这是行不通的,每次调用递归时都必须创建一个新的:

You're reusing the same l list for all the paths, that won't work, you must create a new one every time the recursion gets called:

if (root.left != null) {
    List<TreeNode> acc = new ArrayList<>(l);
    acc.add(root.val);
    rec(root.left, acc, lists);
}

if (root.right != null) {
    List<TreeNode> acc = new ArrayList<>(l);
    acc.add(root.val);
    rec(root.right, acc, lists);
}

这篇关于二叉搜索树路径列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆