简体   繁体   中英

Binary tree search not returning matching value when some nodes are null

TL;DR - How do I alter this algorithm to return the matching val given a BST with null nodes?

TreeNode:

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} val
 * @return {TreeNode}
 */

Given a binary tree, find the matching val. My algorithm is below

var searchBST = function(root, val) {
    const matchingNode = visitNode(root, val);
    // if no match, return null
    return matchingNode ? matchingNode : null;
};

const visitNode = (node, val) => {
    if (node.left !== null) {
        return visitNode(node.left, val)
    }
    if (node.right !== null) {
        return visitNode(node.right, val)
    }
    if (node.val === val) {
        console.log('MATCH!')
        return node;
    }
}

This works for standard trees with no null values, such as [4,2,7,1,3] and empty trees [].

I'm having an issue with trees that have null nodes, such as [18, 2, 22, null, null, null, 63, null, 84, null, null].

The function seems to stop prematurely. If I remove the returns in the first two if blocks, I'm able to stop recursing at the matching val, but unable to get the value to be returned.

How do I alter this algorithm to return the matching val given a BST with null nodes?

You may consider the following refactored version of visitNode() below. The base case occurs when the incoming node be null , in which case the function just returns null . Otherwise, it checks if the current node matches the sought after value. If not, then it traverses either the left or right recursively.

const visitNode = (node, val) => {
    if (node == null) return null;

    if (node.val === val) {
        console.log('MATCH!')
        return node;
    }

    if (val < node.val) {
        return visitNode(node.left, val);
    }
    else {
        return visitNode(node.right, val)
    }
}

If you are looking for binary search tree, try this

if (node == null || node.val === val) 
   return node;
 
// val is greater than node's val
if (node->val < val) 
   return visitNode(node.right, val); 

// val is smaller than node's val
return visitNode(node.left, val); 

Or you have to traverse the tree by DFS or BFS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM