节点结构:
1 class TreeNode(){ 2 3 public String data; 4 5 public TreeNode leftChild; 6 7 public TreeNode rightChild; 8 9 }
前序遍历的一种方法:
1 public void levelOrder3(TreeNode p){ 2 if(p == null) return ; 3 Stack<TreeNode> stack = new Stack<TreeNode>(); 4 TreeNode node = p; 5 stack.push(node); 6 while(!stack.isEmpty()){ 7 node = stack.pop(); 8 visit(node); 9 if(node.rightChild!= null) stack.push(node.rightChild); 10 if(node.leftChild != null) stack.push(node.leftChild); 11 } 12 }
时间: 2024-10-19 07:59:19