zoukankan      html  css  js  c++  java
  • LeetCode 94: Binary Tree Inorder Traversal

    /**
     * 94. Binary Tree Inorder Traversal
     * 1. Time:O(n)  Space:O(n)
     * 2. Time:O(n)  Space:O(n)
     * 3. Time:O(n)  Space:O(1)
     */
    
    // 1. Time:O(n)  Space:O(n)
    class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> res = new LinkedList<>();
            inorderHelper(root,res);
            return res;
        }
        
        public void inorderHelper(TreeNode root, List<Integer> res){
            if(root!=null){
                if(root.left!=null)
                    inorderHelper(root.left,res);
                res.add(root.val);
                if(root.right!=null)
                    inorderHelper(root.right,res);
            }
        }
    }
    
    // 2. Time:O(n)  Space:O(n)
    class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> res = new LinkedList<>();
            Stack<TreeNode> s = new Stack<>();
            TreeNode cur = root;
            while(cur!=null || !s.empty()){
                while(cur!=null){
                    s.push(cur);
                    cur = cur.left;
                }
                cur = s.pop();
                res.add(cur.val);
                cur = cur.right;
            }
            return res;
        }
    }
    
    // 3. Time:O(n)  Space:O(1)
    class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> res = new LinkedList<>();
            TreeNode cur = root;
            TreeNode prev;
            while(cur!=null){
                if(cur.left==null){
                    res.add(cur.val);
                    cur = cur.right;
                }else{
                    prev = cur.left;
                    while(prev.right!=null)
                        prev = prev.right;
                    prev.right = cur;
                    TreeNode tmp = cur;
                    cur = cur.left;
                    tmp.left = null;
                }
            }
            return res;
        }
    }
    
  • 相关阅读:
    数据结构总结——线段树
    [bzoj2131]免费的馅饼 树状数组优化dp
    [机房练习赛7.26] YYR字符串
    博客已搬家
    AFO
    COGS-2551 新型武器
    UVALive-3716 DNA Regions
    UVALive-4850 Installations
    UVALive-3983 Robotruck
    UVA-10859 Placing Lampposts
  • 原文地址:https://www.cnblogs.com/AAAmsl/p/12785806.html
Copyright © 2011-2022 走看看