//广度优先遍历 public void BroadFirstSearch(TreeNode nodeHead) { if(nodeHead==null) { return; } QueuemyQueue=new linkedList<>(); myQueue.add(nodeHead); while(!myQueue.isEmpty()) { TreeNode node=myQueue.poll(); System.out.print(node.data+" "); if(null!=node.leftNode) { myQueue.add(node.leftNode); } if(null!=node.rightNode) { myQueue.add(node.rightNode); } } } //深度优先遍历 public void depthFirstSearch(TreeNode nodeHead) { if(nodeHead==null) { return; } Stack myStack=new Stack<>(); myStack.add(nodeHead); while(!myStack.isEmpty()) { TreeNode node=myStack.pop(); System.out.print(node.data+" "); if(node.rightNode!=null) { myStack.push(node.rightNode); } if(node.leftNode!=null) { myStack.push(node.leftNode); } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)