LeetCode 144: Binary Tree Preorder Traversal

Posted aaamsl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 144: Binary Tree Preorder Traversal相关的知识,希望对你有一定的参考价值。

/**
 * 144. Binary Tree Preorder Traversal
 * 1. Time:O(n)  Space:O(n)
 * 2. Time:O(n)  Space:O(n)
 * 3. Time:O(n)  Space:O(n)
 * 4. Time:O(n)  Space:O(1)
 */

// 1. Time:O(n)  Space:O(n)
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> pre = new LinkedList<>();
        preorderHelper(root,pre);
        return pre;
    }
    
    public void preorderHelper(TreeNode root, List<Integer> pre){
        if(root==null) return;
        pre.add(root.val);
        preorderHelper(root.left,pre);
        preorderHelper(root.right,pre);
    }
}

// 2. Time:O(n)  Space:O(n)
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new LinkedList<>();
        Stack<TreeNode> s = new Stack<>();
        if(root!=null) s.push(root);
        while(!s.empty()){
            TreeNode tmp = s.pop();
            res.add(tmp.val);
            if(tmp.right!=null) s.push(tmp.right);
            if(tmp.left!=null) s.push(tmp.left);
        }
        return res;
    }
}

// 3. Time:O(n)  Space:O(n)
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new LinkedList<>();
        Stack<TreeNode> rights = new Stack<>();
        while(root!=null){
            res.add(root.val);
            if(root.right!=null)
                rights.push(root.right);
            root = root.left;
            if(root==null && !rights.empty())
                root = rights.pop();
        }
        return res;
    }
}

// 4. Time:O(n)  Space:O(1)
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new LinkedList<>();
        TreeNode cur = root;
        while(cur!=null){
            if(cur.left==null){
                res.add(cur.val);
                cur = cur.right;
            }else{
                TreeNode prev = cur.left;
                while(prev.right!=null && prev.right!=cur)
                    prev = prev.right;
                if(prev.right==null){
                    res.add(cur.val);
                    prev.right = cur;
                    cur = cur.left;
                }else if(prev.right==cur){
                    prev.right=null;
                    cur = cur.right;
                }
            }
        }
        return res;
    }
}

以上是关于LeetCode 144: Binary Tree Preorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 144. Binary Tree Preorder Traversal

[leetcode-144-Binary Tree Preorder Traversal]

LeetCode-144-Binary Tree Preorder Traversal

leetcode [144]Binary Tree Preorder Traversal

Java [Leetcode 144]Binary Tree Preorder Traversal

LeetCode 144: Binary Tree Preorder Traversal