zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    第12组 Beta冲刺 (4/5)
    第12组 Beta冲刺 (3/5)
    代码用辅助多了 基础的读取config都忘记了
    wpf 动态添加控件 通过xmal实习 c#代码插入控件
    C#里调用非托管的Dll -z注意 net版本
    动态调用 类库
    c#时间的生成
    c# 第三方 修改版本号 MSBuildTasks, 解决 通配符不匹配问题
    c#.exe以管理员身份运行
    log4
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10232935.html
Copyright © 2011-2022 走看看