LeetCode 94: Binary Tree Inorder Traversal
Posted aaamsl
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}
}
以上是关于LeetCode 94: Binary Tree Inorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode-94-Binary Tree Inorder Traversal]
[LeetCode]94.Binary Tree Inorder Traversal
leetcode 94. Binary Tree Inorder Traversal
LeetCode94 Binary Tree Inorder Traversal