object Test extends App { val queue = new LinkedList[Node] val stack = new Stack[String] queue.add(root) // 假设持有根节点的引用root while (!queue.isEmpty) { for (i <- 0 until queue.size) { val node = queue.poll stack.add(node.toString() + "\t") if (node.left != null) queue add node.left if (node.right != null) queue add node.right } stack.add("\r\n") } stack.foreach(x => print(x)) }
''' Created on Dec 30, 2014 @author: ScottGu<gu.kai.66@gmail.com, 150316990@qq.com> ''' # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of lists of characters def levelOrder(self, root): if(root==None): return [] rslt=[] theLevel=[] theLevel.append(root) while(len(theLevel)>0): rslt.append(theLevel[:]) # deep copy current level # foreach and save next level cnt= len(theLevel) for ix in range(cnt): if(theLevel[0].left!=None): theLevel.append(theLevel[0].left) theLevel.append('\t') if(theLevel[0].right!=None): theLevel.append(theLevel[0].right) theLevel.append('\t') theLevel.pop(0) # remove 1 from this level theLevel.append('\n') # Don't forget to add a line breaker return rslt[::-1]
public class Test { public static void main(String[] args) { Queue<MyNode> queue = new LinkedList<MyNode>(); queue.add(new MyNode(root, 0)); Stack<MyNode> stack = new Stack<MyNode>(); int preLevel = stack.peek().level; while (!stack.isEmpty()) { if (stack.peek().level != preLevel) { System.out.println(); preLevel = stack.peek().level; } System.out.print(stack.pop().node + "\t"); } } public static void travers(Queue<MyNode> queue,Stack<MyNode> stack) { if (queue.peek() == null) return; MyNode mynode = queue.poll(); if (node.left != null) { queue.add(new MyNode(mynode.node.left, mynode.node.level +1)); } if (node.right != null) { queue.add(new MyNode(mynode.node.right, mynode.node.level+ 1)); } stack.push(mynode) } } class MyNode { public Node node; int level; public MyNode(Node node, int level) { this.node = node; this.level = level; } }