700. 二叉搜索树中的搜索【简单】

题目链接

// 工具函数
export const initTree = (inputList: any[]) => {
    const total = inputList.length;
    if(!inputList[0])return null;
    inputList[0] = new TreeNode(inputList[0]);
    inputList.forEach((el: any, index) => {
        let leftP: (null | TreeNode) = null;
        let rightP: (null | TreeNode)  = null;
        if (el === null) return;
        if (index*2+1 < total) {
            leftP = inputList[index*2+1] !== null ? new TreeNode(inputList[index*2+1]): null;
            inputList[index*2+1] = leftP;
        } 
        if (index*2+2 < total) {
            rightP = inputList[index*2+2] !== null ? new TreeNode(inputList[index*2+2]): null;
            inputList[index*2+2] = rightP;
        }
        inputList[index].left = leftP;
        inputList[index].right = rightP;
    });
    return inputList[0];
}

export class TreeNode {
    val: number
    left: TreeNode | null
    right: TreeNode | null
    constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
        this.val = (val===undefined ? 0 : val)
        this.left = (left===undefined ? null : left)
        this.right = (right===undefined ? null : right)
    }
}
// 题解
import { initTree, TreeNode } from './utils/ts-index';

function searchBST(root: TreeNode | null, val: number): TreeNode | null {
    if (!root) return null;
    if (val === root.val) return root;
    if (val < root.val) return searchBST(root.left, val);
    else return searchBST(root.right, val);
};

(()=> {
    const root = initTree([4,2,7,1,3]);
    console.log('searchBST', searchBST(root, 2));
})();

results matching ""

    No results matching ""