Generate a binary tree from parent->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 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
 */
class Relation {
    int parent;
    int child;
    bool isLeft;
};

/**
 * Represents a single Node inside a binary tree
 */
class Node {
    int id;
    Node * left;
    Node * right;
}

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

	public static class Relation {
		public Integer parent, child;
		public boolean isLeft;

		public Relation(Integer parent, Integer child, boolean isLeft) {
			this.parent = parent;
			this.child = child;
			this.isLeft = isLeft;
		}
	}

	public static class Node {
		public Integer val;
		public Node left, right;

		public Node(Integer val, Node left, Node right) {
			this.val = val;
			this.left = left;
			this.right = right;
		}
	}

	private static HashMap<Integer, Node> mapOfNodes;

	public static Node buildTree(List<Relation> relations) {
		mapOfNodes = new HashMap<Integer, Node>();

		Iterator<Relation> relationsIterator = relations.iterator();
		Relation relation;
		Node root = null;

		while (relationsIterator.hasNext()) {
			Node parentNode, childNode;
			relation = relationsIterator.next();

			if (relation.parent == null) {
				root = getChildNode(relation.child);
				continue;
			}

			if (mapOfNodes.containsKey((relation.parent))) {
				parentNode = mapOfNodes.get(relation.parent);
				childNode = getChildNode(relation.child);
				if (relation.isLeft)
					parentNode.left = childNode;
				else
					parentNode.right = childNode;
			} else {
				childNode = getChildNode(relation.child);
				parentNode = new Node(relation.parent, relation.isLeft ? childNode : null, relation.isLeft ? null : childNode);
				mapOfNodes.put(relation.parent, parentNode);
			}
		}

		return root;
	}

	private static Node getChildNode(Integer child) {
		Node childNode;
		if (mapOfNodes.containsKey((child))) {
			childNode = mapOfNodes.get(child);
		} else {
			childNode = new Node(child, null, null);
			mapOfNodes.put(child, childNode);
		}
		return childNode;
	}
}

  

时间: 2024-08-08 01:22:57

Generate a binary tree from parent->child relationship的相关文章

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

Binary Tree Longest Consecutive Sequence

Given a binary tree, find the length of the longest consecutive sequence path. The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from p

[LeetCode] Binary Tree Upside Down

Problem Description: Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into le

Binary Tree Longest Consecutive Sequence Leetcode

Given a binary tree, find the length of the longest consecutive sequence path. The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from p

Verify Preorder Serialization of a Binary Tree

One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #. _9_ / 3 2 / \ / 4 1 # 6 / \ / \ / # # # # # # For examp

【DataStructure】Implemantation of Binary Tree

Statements: This blog was written by me, but most of content  is quoted from book[Data Structure with Java Hubbard] Here is a class for binary trees that directly implements the recursive definition. By extending the AbstractCollectionclass, it remai

[LeetCode] Construct Binary Tree from String 从字符串创建二叉树

You need to construct a binary tree from a string consisting of parenthesis and integers. The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and

[Locked] Binary Tree Longest Consecutive Sequence

Binary Tree Longest Consecutive Sequence Given a binary tree, find the length of the longest consecutive sequence path. The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The l

Leetcode: Binary Tree Longest Consecutive Sequence

Given a binary tree, find the length of the longest consecutive sequence path. The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from p