Since it is guaranteed that each inner node has exactly 2 children, we can simply build the tree recursively using this.
We call our function with the input provided, and it checks the first character that it received. If it is a leaf node, it just returns the leaf. If it is an internal node, it simply calls itself for the left and right subtrees and returns the tree formed with node as root, and the left and right subtrees as its left and right child elements.
The following is the code (in Python). Please note: I am using tuple to represent node, therefore the tree is tuple tuples .
#! /usr/bin/env python from collections import deque def build_tree(pre_order): root=pre_order.popleft() if root=='L': return root else: return (root,build_tree(pre_order),build_tree(pre_order)) if __name__=='__main__': print build_tree(deque("NNLLL"))
Edit: Java code
import java.util.*; class Preorder{ public static Node buildTree(List<Character> preorder){ char token=preorder.remove(0); if (token=='L'){ return new Node(token,null,null); } else{ return new Node(token,buildTree(preorder),buildTree(preorder)); } } public static void main(String args[]){ List<Character> tokens=new LinkedList<Character>(); String input="NNLLL"; for(int i=0;i<input.length();i++) tokens.add(input.charAt(i)); System.out.println(buildTree(tokens)); } } class Node{ char value; Node left,right; public Node(char value, Node left, Node right){ this.value=value; this.left=left; this.right=right; } public String toString(){ if (left==null && right==null){ return "("+value+")"; } else{ return "("+value+", "+left+", "+right+")"; } } }
source share