本文主要是介绍二叉树 - 二叉搜索树中的搜索,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
700. 二叉搜索树中的搜索
递归:
/*** 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}*/
var searchBST = function (root, val) {if (!root || root.val === val) {return root;}if (root.val > val) {return searchBST(root.left, val);}if (root.val < val) {return searchBST(root.right, val);}
};
迭代:
/*** 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}*/
var searchBST = function (root, val) {while (root !== null) {if (root.val > val) {root = root.left;} else if (root.val < val) {root = root.right;} else {return root;}}return null;
};
这篇关于二叉树 - 二叉搜索树中的搜索的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!