zprill 2009-03-28 22:32
浏览 180
已采纳

我想问一个递归的问题,应该是树的递归吧

id paredntid
1 0
2 1
3 1
4 2
5 3

这样一组数据,假设已经放在list里了,如何封装成{1,{2{4}},{3{5}}}.
哪位兄弟指点迷津下,谢谢

  • 写回答

1条回答 默认 最新

  • rednaxelafx 2009-03-29 02:46
    关注

    遍历树的过程通常可以用递归来实现,但是遍历一个list来构造一棵树纯粹是线性的遍历而已……

    简单实现了一个版本:
    [code="java"]import java.util.*;

    class TreeNode {
    // don't need a reference to parent for an ordinary tree
    //private TreeNode parent;

    // a list of children TreeNodes, implementing an N-ary tree
    private List<TreeNode> children;
    
    // use this field to carry values on all nodes
    private E value;
    
    public TreeNode() {
        this(null);
    }
    
    public TreeNode(E value) {
        this.value = value;
        this.children = new ArrayList<TreeNode>();
    }
    
    public TreeNode(E value, Iterable<TreeNode> children) {
        this(value);
        // add all children
        // can't use List<E>.addAll() because Iterable<E> is
        // a base interface of Collection<E>
        for (TreeNode child : children) {
            addChild(child);
        }
    }
    
    public E getValue() {
        return this.value;
    }
    
    public void setValue(E value) {
        this.value = value;
    }
    
    public Iterable<TreeNode> getChildren() {
        return this.children;
    }
    
    public void addChild(TreeNode child) {
        // skip duplicate children
        if (!this.children.contains(child)) {
            this.children.add(child);
        }
    }
    
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        toStringCore(sb);
        return sb.toString();
    }
    
    // builds the string recursively
    protected void toStringCore(StringBuilder sb) {
        sb.append("(");
        sb.append(value);
        for (TreeNode child : this.children) {
            sb.append(" ");
            child.toStringCore(sb);
        }
        sb.append(")");
    }
    

    }

    public class TestTree {
    private static Map getSampleNodeMapping() {
    return new HashMap() {{
    put(1, 0);
    put(2, 1);
    put(3, 1);
    put(4, 2);
    put(5, 3);
    }};
    }

    private static TreeNode<Integer> buildTreeFromMapping(
        Map<Integer, Integer> mapping) {
    
        // make a map from id to TreeNode instance
        Map<Integer, TreeNode<Integer>> nodes
            = new HashMap<Integer, TreeNode<Integer>>();
        TreeNode<Integer> root = null;
        for (Map.Entry<Integer, Integer> entry : mapping.entrySet()) {
            Integer key = entry.getKey();
            Integer value = entry.getValue();
            TreeNode<Integer> child = null;
            if (!nodes.containsKey(key)) {
                child = new TreeNode<Integer>(key);
                nodes.put(key, child);
            } else {
                child = nodes.get(key);
            }
            if (0 == value) {
                root = child;
            } else {
                TreeNode<Integer> parent = null;
                if (!nodes.containsKey(value)) {
                    parent = new TreeNode<Integer>(value);
                    nodes.put(key, parent);
                } else {
                    parent = nodes.get(value);
                }
                parent.addChild(child);
            }
        }
    
        return root;
    }
    
    public static void main(String[] args) {
        Map<Integer, Integer> mapping = getSampleNodeMapping();
        TreeNode<Integer> root = buildTreeFromMapping(mapping);
        System.out.println(root); // (1 (2 (4)) (3 (5)))
    }
    

    }[/code]
    这段代码遍历一个id到parent_id的映射表并创建出对应的树,这个遍历过程是线性的;在得到树的字符串表示(toString)时遍历了树,过程是递归的。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入