leetCode 109 construct a height-balanced Binary Search tree from input array(sorted or not).
a self-balanced BStree, which means the left and right kid of each node have no more than 1 height difference, also named as AVL tree. There are three basic routines in implementation of AVL tree: right tree rotate, left tree rotate, and insert. and each TreeNode requires an additionly height
value.
|
|
at the very first coding I natively pass node pointer by reference:
TreeNode* insert(TreeNode* &root, int key)
root->right = insert(root->right, key);
since assigned insert() back to the same node pointer again, if passing by reference, each insert will clear the memory-write the same memory all the time, and can’t generate. what actually happen in insert
is creating a new object.
the structure pointer inside structure definition is the trick here. when define root
node, both left
and right
nodes are nullptr
, so argument root->right
is nullptr
, but the returning root->right
is actually pointing to a node structure memory.
also nullptr can’t be dereferring, basically since nullptr doesn’t point to any meaningful object, to dereference a null pointer will cause runtime or immediate crash.