标签: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