Binary Tree

1. traverse

binary traverse

2. path

bst path

3. serialization

binary tree serialization

4. reconstruct tree from traverse

binary tree reconstruct tree from traverse

5. conversion between tree and linked list

binary tree conversion between tree and linked list

6. misc

binary tree misc topics

Add a New Comment
or Sign in as Wikidot user
(will not be published)
- +

7. cloest value

http://stackoverflow.com/questions/6209325/how-to-find-the-closest-element-to-a-given-key-value-in-a-binary-search-tree

Tnode * closestBST(Tnode * root, int val){
    if(root->val == val)
        return root;
    if(val < root->val){
        if(!root->left)
            return root;
        Tnode * p = closestBST(root->left, val);
        return abs(p->val-val) > abs(root->val-val) ? root : p;
    }else{
        if(!root->right)
            return root;
        Tnode * p = closestBST(root->right, val);
        return abs(p->val-val) > abs(root->val-val) ? root : p;
    }   
    return null;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License