• 144. Binary Tree Preorder Traversal


    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?

    M1: recursive

    time: O(n), space: O(height)

    /**
     * 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> res = new ArrayList<>();
            preorder(root, res);
            return res;
        }
        
        public void preorder(TreeNode root, List<Integer> res) {
            if(root == null) {
                return;
            }
            res.add(root.val);
            preorder(root.left, res);
            preorder(root.right, res);
        }
    }

    M2: iterative

    time: O(n), space: O(n)  -- depending on the tree structure, could keep up to the entire tree

    /**
     * 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> res = new ArrayList<>();
            LinkedList<TreeNode> s = new LinkedList<>();
            if(root == null) {
                return res;
            }
            
            s.offerFirst(root);
            while(!s.isEmpty()) {
                TreeNode cur = s.pollFirst();
                res.add(cur.val);
                if(cur.right != null) {
                    s.offerFirst(cur.right);
                }
                if(cur.left != null) {
                    s.offerFirst(cur.left);
                }
            }
            return res;
        }
    }
  • 相关阅读:
    第一周博客作业(学习历程和感想)
    WordCount 基础功能
    MyBatis 分页插件 PageHelper 使用
    手机尾号猜年龄骗局解密
    逻辑思维题一
    给div添加滚动条
    my97中文乱码问题
    cookie中文乱码
    多线程下的单例模式
    HTML5的入门与深入理解
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10232935.html
Copyright © 2020-2023  润新知