Leetcode 144. Binary Tree Preorder Traversal

题目链接

https://leetcode.com/problems/binary-tree-preorder-traversal/description/

题目描述

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

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,2,3]

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

题解

使用一个栈来保存数据,把每一个节点的子节点依次入栈,先右节点,再左节点。

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new LinkedList<>();
        if (root == null) { return list; }
        Stack<TreeNode> s = new Stack<>();
        s.push(root);
        while (!s.isEmpty()) {
            TreeNode node = s.pop();
            list.add(node.val);
            if (node.right != null) { s.push(node.right); }
            if (node.left != null) { s.push(node.left); }
        }
        return list;
    }
}

posted @ 2018-09-07 11:39  DCREN  阅读(157)  评论(0编辑  收藏  举报