Tree

General template for various tree questions. Source

Inorder Traversal ```java public List inorderTraversal(TreeNode root) { List list = new ArrayList<>(); if(root == null) return list; Stack stack = new Stack<>(); while(root != null || !stack.empty()){ while(root != null){ stack.push(root); root = root.left; } root = stack.pop(); list.add(root.val); root = root.right;

}
return list; } ```

Problems

  1. Validate BST
public boolean isValidBST(TreeNode root) {
   if (root == null) return true;
   Stack<TreeNode> stack = new Stack<>();
   TreeNode pre = null;
   while (root != null || !stack.isEmpty()) {
      while (root != null) {
         stack.push(root);
         root = root.left;
      }
      root = stack.pop();
      if(pre != null && root.val <= pre.val) return false;
      pre = root;
      root = root.right;
   }
   return true;
}
Written on July 25, 2020