How to implement a inorder traversal of a BST returning a li
How to implement a inorder traversal of a BST returning a list? Basically public List inorder() {}
Solution
In order traversal using list we can use stack .inorder check current node is empty
Traverse left subtree by recursively calling the function
Add to list
Traverse right subtree by calling recursively function and store in list.
public List<Integer> inorder(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
while(!stack.isEmpty() || root!=null){
if(root!=null){
stack.push(root);
root=root.left;
}else{
root = (TreeNode) stack.pop();
list.add(root.val);
root = root.right;
}
}
return list;
}
