Leetcode 700 二叉搜尋樹中的搜尋
阿新 • • 發佈:2020-12-14
Leetcode 700 二叉搜尋樹中的搜尋
題目定義:
給定二叉搜尋樹(BST)的根節點和一個值。 你需要在BST中找到節點值等於給定值的節點。
返回以該節點為根的子樹。 如果節點不存在,則返回 NULL。
例如,
給定二叉搜尋樹:
4
/ \
2 7
/ \
1 3
和值: 2
你應該返回如下子樹:
2
/ \
1 3
在上述示例中,如果要找的值是 5,但因為沒有節點值為 5,我們應該返回 NULL。
遞迴方式:
class Solution { private TreeNode node; public TreeNode searchBST(TreeNode root, int val) { if(root == null) return null; dfs(root,val); return node; } private void dfs(TreeNode root,int val){ if(root == null) return; if(root.val == val) node = root; if(root.val > val) dfs(root.left,val); else dfs(root.right,val); } }
另一種簡便遍歷方式:
class Solution { public TreeNode searchBST(TreeNode root, int val) { if(root == null) return null; return root.val == val ? root : root.val > val ? searchBST(root.left,val) : searchBST(root.right,val); } }
迭代方式:
class Solution { public TreeNode searchBST(TreeNode root, int val) { if(root == null) return null; while(root != null){ if(root.val == val) return root; else if(root.val > val) root = root.left; else root = root.right; } return root; } }