[leetcode] 144. 二叉树的前序遍历

144. 二叉树的前序遍历

递归写法

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        dfs(root, list);
        return list;
    }

    public void dfs(TreeNode node, List<Integer> ans) {
        ans.add(node.val);
        if (node.left != null) dfs(node.left, ans);
        if (node.right != null) dfs(node.right, ans);
    }
}

非递归写法

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();

        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                list.add(root.val);
                stack.add(root);
                root = root.left;
            }
            if (!stack.isEmpty()) {
                root = stack.pop();
                root = root.right;
            }
        }

        return list;
    }

   
}
posted @ 2018-08-07 22:27  ACBingo  阅读(417)  评论(0编辑  收藏  举报