二叉树先序非递归遍历

2018/08/13 Offer 共 752 字,约 3 分钟

title

problem link

Given a binary tree, return the preorder traversal of its nodes’ values.

For example: Given binary tree{1,#,2,3},

   1
    \
     2
    /
   3

return[1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

solution

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        ArrayDeque<TreeNode> stack=new ArrayDeque<>();
        if(root==null) return new ArrayList<>();
        TreeNode p=root;
        ArrayList<Integer> res=new ArrayList<>();
        while (p!=null||!stack.isEmpty()){
            while (p!=null){
                res.add(p.val);
                stack.push(p);
                p=p.left;
            }
            if(!stack.isEmpty()){
                p=stack.peek().right;
                stack.pop();
            }
           // System.out.print("1");
        }
        return res;
    }
}

Search

    Table of Contents