2019.4.1
//exercise 25.4
public void preorderUsingStack(){
preorderUsingStack(root);
}
private void preorderUsingStack(TreeNode<T> root){
if(root == null)
return;
Stack<TreeNode<T>> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()){
TreeNode<T> current = stack.pop();
System.out.print(current.element+" ");
if(current.right != null){
stack.push(current.right);
}
if(current.left != null){
stack.push(current.left);
}
}
}

本文介绍了一种使用栈数据结构实现二叉树先序遍历的方法。通过递归思想,将根节点压入栈中,然后不断从栈中弹出节点并访问,再将其右子树和左子树按顺序压入栈中,直至栈为空,完成遍历。
3269

被折叠的 条评论
为什么被折叠?



