码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 94: Binary Tree Inorder Traversal

时间:2020-04-27 13:26:00      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:lis   return   help   bin   class   while   ==   push   val   

/**
 * 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;
    }
}

LeetCode 94: Binary Tree Inorder Traversal

标签:lis   return   help   bin   class   while   ==   push   val   

原文地址:https://www.cnblogs.com/AAAmsl/p/12785806.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!