We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,111 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Time Complexity for Constructing Binary Tree

Hi, I am trying to create a binary tree from a string read from a file. The string contains information that tells which is the new left and right nodes, and the node which new these nodes are to be added (assuming there is a root node in the tree already). To find the node of where the 2 new nodes should be added, I used preorder tree traversal:

public void iterativePreorder(Node root) {
        Stack nodes = new Stack();
        nodes.push(root);

        Node currentNode;

        while (!nodes.isEmpty()) {
                currentNode = nodes.pop();
                Node right = currentNode.right();
                if (right != null) {
                        nodes.push(right);
                }
                Node left = currentNode.left();
                if (left != null) {
                        nodes.push(left);      
                }
                System.out.println("Node data: "+currentNode.data);
        }
}

This is from Wikipedia's Tree Traversal page but mine is does the same thing except it returns the node rather than print it. The complexity of preorder traversal is O(n). So my question is, if there are n nodes in the file to add to the tree, and for each node I have to call the above code, does that mean the contruction of the whole tree will be O(n^2)?

2
Contributors
1
Reply
6 Hours
Discussion Span
1 Year Ago
Last Updated
2
Views
DanHu
Newbie Poster
4 posts since Sep 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Yes, this is O(n^2). You basically have 2 loops: an outer loop of nodes to add to the tree and an inner loop of nodes already in the tree. The outer shrinks while the inner grows, but overall you will average O(n^2) for really large number of nodes.

ztini
Posting Whiz in Training
299 posts since Jan 2011
Reputation Points: 51
Solved Threads: 53
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0767 seconds using 2.74MB