*Tree child->parent relationships

Given a list of child->parent relationships, build a binary tree out of it. All the element Ids inside the tree are unique.

Example:

Given the following relationships:

Child Parent IsLeft 
15 20 true 
19 80 true 
17 20 false 
16 80 false 
80 50 false 
50 null false 
20 50 true

You should return the following tree: 
50 
/ \ 
20 80 
/ \ / \ 
15 17 19 16

Function Signature

/** 
* Represents a pair relation between one parent node and one child node inside a binary tree 
* If the _parent is null, it represents the ROOT node 
*/ 
public class Relation { 
public Integer _parent; 
public Integer _child; 
public boolean _isLeft; 
}

/** 
* Represents a single Node inside a binary tree 
*/ 
public class Node { 
public Integer _id; 
public Node _left; 
public Node _right; 
}

/** 
* Implement a method to build a tree from a list of parent-child relationships 
* And return the root Node of the tree 
*/ 
public Node buildTree (List<Relation> data) 

}

解法一:One simple approach to this problem can be: we know the ROOT of the tree is the one where the parent is null in the list. Once we figure out the parent, we can iteratively figure out its children and their children- by looping over the complete list and finding out the ones that point the current node as its parent. To build tree efficiently, we can use queue to keep track of the tree built till then. The running time would be O(n^2), with constant space (not really, we are keeping a queue as well)

public static Node buildTree(List<Relation> data){
        if(data==null) return new Node();
        Node root=new Node();
        int children=0;
        for(int i=0;i<data.size();i++){
            Relation x=data.get(i);
            if(x.parent==null){
                root=new Node(x.child,null,null);
                break;
            }
        }
        if(root==null) return root;
        Queue<Node> q=new LinkedList<Node>();
        q.add(root);
        while(!q.isEmpty()){
            Node x=q.poll();
            for(int i=0;i<data.size();i++){
                Relation y=data.get(i);
                if(y.parent==x.id){
                    Node n=new Node(y.child,null,null);
                    if(y.isLeft)
                        x.left=n;
                    else x.right=n;
                    q.add(n);
                    children++;
                    if(children==2){
                        children=0;
                        break;
                    }
                }
            }
        }
        return root;
    }

解法二:

Another way to approach this problem for a better running time could be by using a HashMap. We can hash the list with key as the parent and value as a list of its children. And then iteratively generating the tree. This solution would be O(n) time complexity and O(n) space complexity.

public static Node buildTree(List<Relation> data){
        if(data==null) return new Node();
        Node root=new Node();
        HashMap<Integer,ArrayList<Relation>> tree = new HashMap<Integer,ArrayList<Relation>>();
        for(Relation d:data){
            if(d.parent==null)
                root=new Node(d.child,null,null);
            else{
                if(tree.containsKey(d.parent)){
                    ArrayList<Relation> value=tree.get(d.parent);
                    value.add(d);
                } else {
                    ArrayList<Relation> value = new ArrayList<Relation>();
                    value.add(d);
                    tree.put(d.parent,value);
                }
            }
        }
        if(root==null) return root;
        Queue<Node> q = new LinkedList<Node>();
        q.add(root);
        while(!q.isEmpty()){
            Node x = q.poll();
            if(tree.containsKey(x.id)){
                ArrayList<Relation> value=tree.get(x.id);
                for(Relation v:value){
                    Node child = new Node(v.child,null,null);
                    q.add(child);
                    if(v.isLeft)
                        x.left=child;
                    else x.right=child;
                }
            }
        }
        return root;
    }

reference:

http://www.careercup.com/question?id=5668114807128064

时间: 2024-08-24 13:57:32

*Tree child->parent relationships的相关文章

Lowest Common Ancestor of a Binary Tree, with Parent Pointer

Given a binary tree, find the lowest common ancestor of two given nodes in tree. Each node contains a parent pointer which links to its parent. int getHeight(Node* p) { int height = 0; while (p) { height++; p = p->parent; } return height; } Node* LCA

C高级 框架开发中红黑树结构

引言  -- 红黑树历史 红黑树是数据结构学习中一道卡. 底层库容器中必不可少的算法. 历经各种实战运用,性能有保障. 同样红黑树不好理解, 就算理解了, 代码也不好写. 就算写了, 工程库也难构建. 关于红黑树基础讲解推荐看下面博主的红黑树博文系列,感觉不错. 红黑树(一)之 原理和算法详细介绍 对于红黑树小背景简介摘抄如下: 红黑树(英语:Red–black tree)是一种自平衡二叉查找树,是在计算机科学中用到的一种数据结构,典型的用途是实现关联数组.它是在1972年由鲁道夫·贝尔发明的,

二叉树之红黑树(RBTree)

详解以后再补充... 红黑树和AVL树6层模式下的最少结点数 通过图可以看到红黑树可以实现更少的结点,反过来说就是同样的结点数红黑树最大数高会超过AVL树 https://www.cs.usfca.edu/~galles/visualization/Algorithms.html这个网站可以测试动态效果,下图就是截图于此 红黑树插入删除步骤 输出 代码 其余代码:https://github.com/Duacai/Data-Structure-and-Algorithms/tree/master

Generate a binary tree from parent-&gt;child relationship

This was asked in LinkedIn Interview Given a list of child->parent relationships, build a binary tree out of it. All the element Ids inside the tree are unique. Example: Given the following relationships: Child Parent IsLeft 15 20 true 19 80 true 17

ExtJS笔记 Tree

The Tree Panel Component is one of the most versatile Components in Ext JS and is an excellent tool for displaying heirarchical data in an application. Tree Panel extends from the same class as Grid Panel, so all of the benefits of Grid Panels - feat

JQuery EasyUi Tree获取所有checkbox选中节点的id和内容

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html>    <head>        <meta name="generator" content="HTML Tidy, see www.w3.org">      

[lintcode easy]Binary Tree Postorder Traversal

Binary Tree Postorder Traversal Given a binary tree, return the postorder traversal of its nodes' values. Given binary tree {1,#,2,3}, 1 2 / 3 return [3,2,1]. Challenge Can you do it without recursion? Among preorder,inorder and postorder binary tree

翻译 - 【Dojo Tutorials】Connecting a Store to a Tree

原文:Connecting a Store to a Tree Dojo Tree组件是一个强大的展示层级数据的工具.该教程将展示如何连接tree与store来快速有效的展示层级数据. 介绍 Dojo Tree组件为展示层级数据提供了一种综合的,熟悉的,直观的方式.它将展示与数据分离.本文将提到为驱动一个tree提供数据的多种方法. 第一个例子使用一个静态tree,其数据从一个JSON文件中获取.这可以用于通过数据提供导航.第二个例子在这个设计的基础上扩展新的强大功能,如拖拽,维护一个动态的tr

863.&#160;All Nodes Distance K in Binary Tree

https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/143752/JAVA-Graph-+-BFS https://www.youtube.com/watch?v=o1siL8eKCos class Solution { Map<TreeNode, List<TreeNode>> map = new HashMap(); //here can also use Map<TreeNo