//迭代遍历 前序
public static void fororder(TreeNode root){
if (root != null){
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.add(root);
while (stack != null){
root = stack.pop();//取出栈顶元素
if (root!=null){
System.out.println(root.val);
stack.push(root.right);
stack.push(root.left);
}
}
}
}
//迭代遍历 层序
public static void forendorder(TreeNode root){
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()){
TreeNode node = q.poll();
if(node != null){
System.out.println(node.val);
q.add(node.left);
q.add(node.right);
}
}
}
二叉树遍历