의 프리앰블 후 비 재귀 이진 트리 탐색

심플 전에 주문 후 이진 트리 탐색을 달성하기 위해 재귀 방법, 우리는 매우 간단한 재귀 문을 사용할 필요가 함수 스택은 자동으로 복잡한 작업을 수행하는 데 도움이 될 것입니다. 전면 postorder 주사로 이진 트리의 비순환 방법을 사용하여, 본질적으로 인간 시뮬레이션 기능 스택 스택을 생성한다.

1. 예약 주문 탐색 비 재귀

  1. 스택 애플리케이션 스택 및 스택 헤드 노드로 가압된다.

  2. (다음 버리지), 스택, 인쇄에서 다음 오른쪽 자식 노드를 스택 노드를 팝업 스택에 압입하고, (빈되지 않은 경우) 마침내 왼쪽 자식 노드에 스택에 누를 수.

  3. 스택이 비어있을 때까지 2 단계, 전체 프로세스 종료를 반복한다.

private static void firstSearch(TreeNode t){

        Stack<TreeNode> stack = new Stack<>();
        // 先放根,然后pop出来放右节点和左节点,然后重复上述操作
        stack.push(t);
        while(!stack.isEmpty()){
            TreeNode temp = stack.peek();
            stack.pop();
            System.out.println(temp.val);
            if(temp.right != null){
                stack.push(temp.right);
            }
            if(temp.left != null){
                stack.push(temp.left);
            }
        }
    }

비 재귀 통과를 달성하기 2에서 오더

  1. 스택 스택을 적용, 초기 계절 CUR = 머리

  2. 제 스택으로 푸시 CUR 왼쪽 경계 순차 스택으로 푸시된다, 즉, t = t.left를 유지하도록 반복 단계 2

  3. 2 반복 2 단계, 노드, 잉크의 노드 값이라 널 스택에서 팝 노드가 될 때까지 반복하고,이 t = node.right하자

  4. 스택이 비어 있고 t이 비어있는 경우, 프로세스가 중지됩니다.


private static void midSearch(TreeNode t){
        Stack<TreeNode> stack = new Stack<>();
        // 首先不断入栈顶节点的左节点,直到入不了为止,然后pop出栈顶节点,入一个右节点,然后入该右节点的左子节点直到
        // 入不了为止,重复上述步骤
        if(t != null){
            while(t != null || !stack.isEmpty()){
                if(t != null){
                    stack.push(t);
                    t = t.left;
                }else{
                    System.out.println(stack.peek().val);
                    t = stack.pop().right;
                }
            }
        }
    }

3. 비 postorder 재귀

  1. 스택 S1, S1의 스택에 그 머리 노드를 적용한다.

  2. 다음 팝업-S1 온도, 온도로 기록 노드에서 왼쪽 자식 노드와 밀어 우측 자식 노드 (S1)을 설정합니다.

  3. 프로세스 전체에서, 각 노드 (S1)로부터 배출되고 (S2)가 배치됩니다.

  4. S1까지 단계 2 및 3을 반복하여 비어, 프로세스는 정지한다.

  5. 순차적으로 인쇄 노드와 S2에서 배출, 주문 후 인쇄 순서는 통과된다.


private static void lastSearch(TreeNode t){
        // 仿照先序遍历的相反顺序,但是pop出来后需要放入另一个栈中
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        stack1.push(t);
        while(!stack1.isEmpty()){
            TreeNode temp = stack1.peek();
            stack2.push(stack1.pop());
            if(temp.left != null){
                stack1.push(temp.left);
            }
            if(temp.right != null){
                stack1.push(temp.right);
            }
        }
        while(!stack2.isEmpty()){
            System.out.println(stack2.pop().val);
        }
    }

추천

출처www.cnblogs.com/Water2Wine/p/12580860.html