zoukankan      html  css  js  c++  java
  • LeetCode144. 二叉树的前序遍历

    思路1:递归。

    思路2:非递归。使用栈模拟递归。

    class Solution {
        public List<Integer> preorderTraversal(TreeNode root) {
            /**
             *方法1:递归
             *  时间复杂度O(n)
             *  空间复杂度O(n)为递归中栈的开销,平均情况为 O(logn),最坏情况下树呈现链状,为 O(n)
             */
            /*
            List<Integer> res = new ArrayList<>();
            dfs(root, res);
            return res;
            */
            /**
             * 方法2:非递归,使用栈模拟递归
             *      时间复杂度O(n)
             *      空间复杂度O(n)为迭代过程中显式栈的开销
             */
            List<Integer> res = new ArrayList<>();
            Stack<TreeNode> stack = new Stack<>();
            while (!stack.isEmpty() || root != null) {
                while (root != null) {
                    res.add(root.val);
                    stack.push(root);
                    root = root.left;
                }
                root = stack.pop();
                root = root.right;
            }
            return res;
        }
        private void dfs(TreeNode root, List<Integer> res) {
            if (root == null) return;
            res.add(root.val); //
            dfs(root.left, res); //
            dfs(root.right, res); //
        }
    }
  • 相关阅读:
    AbsoluteLayout 相框
    Cursor getContentResolver
    Diary DiaryDbAdapter 日记本程序
    Linkify
    Installation error: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED
    exampleuse SharedPreferences
    Gallery
    AbsoluteLayout xiantu
    PRD
    android 拨打电话 号码判断
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/14156838.html
Copyright © 2011-2022 走看看