leetcode 144. Binary Tree Preorder Traversal

recursive version

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<Integer> ret = new ArrayList<>();
    public List<Integer> preorderTraversal(TreeNode root) {
        dfs(root);
        return ret;
    }
    
    public void dfs(TreeNode node) {
        if (node == null) return;
        ret.add(node.val);
        dfs(node.left);
        dfs(node.right);
    }
}

Non-recursive. It's relatively simple. So no explaination.

/**
 * 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> ret = new ArrayList<>();
        if (root == null) return ret;
        Stack<TreeNode> s = new Stack<TreeNode>();
        s.add(root);
        while (!s.isEmpty()) {
            TreeNode node = s.pop();
            ret.add(node.val);
            if (node.right != null) s.add(node.right);
            if (node.left != null) s.add(node.left);
        }
        return ret;
    }
}
posted on 2019-04-10 10:58  王 帅  阅读(97)  评论(0编辑  收藏  举报