二分搜索树 08 非递归的前序遍历

二分搜索树的非递归前序遍历

  • 用非递归的方式前序遍历二分搜索树,需要借助一个栈;
  • 先把根节点压入栈;
  • 只要栈不为空:
    • 弹出栈顶节点
    • 如果栈顶节点有右孩子,压入右孩子;
    • 如果栈顶节点有左孩子,压入左孩子;
要点
  • 最后想处理的,先放进栈里面;
// 二分搜索树的非递归前序遍历
public void preOrderNR(){
    if(root == null)
        return;

    Stack stack = new Stack<>();
    stack.push(root);
    while(!stack.isEmpty()){
        Node cur = stack.pop();
        System.out.println(cur.e);

        if(cur.right != null)
            stack.push(cur.right);
        if(cur.left != null)
            stack.push(cur.left);
    }
}

你可能感兴趣的:(二分搜索树 08 非递归的前序遍历)