/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ classSolution{ TreeNode result = null;
public TreeNode searchBST(TreeNode root, int val){ search(root, val); return result; }
voidsearch(TreeNode node, int target){ if (node == null) return; if (target == node.val) { result = node; return; } if (target > node.val) searchBST(node.right, target); if (target < node.val) searchBST(node.left, target); } }
简洁版本:
1 2 3 4 5 6 7 8
classSolution{ public TreeNode searchBST(TreeNode root, int val){ if (root == null || root.val == val) return root; if (root.val > val) return searchBST(root.left, val); elseif (root.val < val) return searchBST(root.right, val); elsereturn root; } }