public class TreeNode {
TreeNode right;
TreeNode left;
int val;
}
import java.util.Stack;
public class PreOrder {
/*
* 递归
*/
public void preorder(TreeNode root){
if(root == null)
return;
System.out.println(root.val);
preorder(root.left);
preorder(root.right);
}
/*
* 非递归
*/
public static void preorder2(TreeNode root){
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode temp = stack.pop();
System.out.println(temp.val);
if(temp.right != null)
stack.push(temp.right);
if(temp.left!=null)
stack.push(temp.left);
}
}
}
时间: 2024-10-12 03:59:14