Created
December 7, 2011 08:17
-
-
Save thinkphp/1441966 to your computer and use it in GitHub Desktop.
Breadth-First Traversal of a Binary Tree.MooTools JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * @author Adrian Statescu <mergesortv@gmail.com> | |
| * MIT Style License | |
| */ | |
| var Node = new Class({ | |
| initialize: function(info) { | |
| this.info = info; | |
| this.left = null; | |
| this.right = null; | |
| this.level = null; | |
| }, | |
| toString: function() { | |
| return this.info; | |
| } | |
| }); | |
| function BFT(node) { | |
| node.level = 1; | |
| var queue = [node], | |
| output = [], | |
| current_level = node.level; | |
| while(queue.length > 0) { | |
| current_node = queue.shift(); | |
| if(current_node.level > current_level) { | |
| current_level++; | |
| output.push("\n"); | |
| } | |
| output.push(current_node + " "); | |
| if(current_node.left) { | |
| current_node.left.level = current_level + 1; | |
| queue.push(current_node.left); | |
| } | |
| if(current_node.left) { | |
| current_node.right.level = current_level + 1; | |
| queue.push(current_node.right); | |
| } | |
| } | |
| return output.join(""); | |
| } | |
| var root = new Node(9); | |
| root.left = new Node(8); | |
| root.right = new Node(7); | |
| root.left.left = new Node(2); | |
| root.left.right = new Node(4); | |
| root.right.left = new Node(6); | |
| root.right.right = new Node(8); | |
| root.left.left.left = new Node('a'); | |
| root.left.left.right = new Node('b'); | |
| root.left.right.right = new Node('c'); | |
| alert(BFT(root)); | |
| /* | |
| 9 | |
| 8 7 | |
| 2 4 6 8 | |
| a b c | |
| 9 | |
| 8 7 | |
| 2 4 6 8 | |
| a b c | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment