Increasing Order Search Tree -- Leetcode #897

preview_player
Показать описание
Hi, everyone! This is Yili. Today we are going to talk about how to use Stack to do in-order traversal. Hope you enjoy it!
Рекомендации по теме
Комментарии
Автор

Since we are only storing the stack using extra space, shouldn't the space complexity be O(h)?

sourabhbagrecha
Автор

how does anyone come up with recursive solutions. it takes me alot to come up with solution until and unless i look up solutions

cupidchakma
Автор

you can maintain only one while loop check this code. I wrote after watching your video.
class Solution {
public TreeNode increasingBST(TreeNode root)
{
if(root == null)
return null;
Stack<TreeNode> s = new Stack<>();
TreeNode head = null;
TreeNode curr = null;
s.add(root);
while(!s.isEmpty())
{
if(root.left!= null)
{
s.push(root.left);
root = root.left;
}
else
{
TreeNode temp = s.pop();
if(head == null)
{
head = new TreeNode(temp.val);
curr = head;
}
else
{
curr.right = new TreeNode(temp.val);
curr = curr.right;
}
if(temp.right != null)
{
s.push(temp.right);
root = temp.right;
}
}
}
return head;

}
}

sivakingable
welcome to shbcf.ru