二叉树的先序、后序遍历(非递归)

阅读 114

2022-01-16

思路:
1.弹出则打印
2.如有右,压入右
3.如有左,压入左

public void pre(Node head){
    
    Stack<Node> stack = new Stack<>();
    stack.push(head);
    while(!stack.isEmpty()){
        head = stack.pop();
        System.out.println(head.val);
        if(head.right != null){
            stack.push(head.right);
        }
        if(head.left != null){
            stack.push(head.left);
        }
    }
        
}

后序遍历和前序遍历差不多,只需要先压入左再压入右,最后把结果反转一下即可

精彩评论(0)

0 0 举报