TreeNode
类只定义了左右子项。
public class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int val) {
this.val = val;
}
}
我的代码找到O(n)中的下一个最低节点。我想知道是否有可能在lg(N)中找到它,因为节点没有指向其父节点的指针。
// run time O(n)
public static Integer findNextLowest(TreeNode root, int target) {
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || stack.size() > 0) {
while (cur != null) {
stack.push(cur);
cur = cur.right;
}
TreeNode node = stack.pop();
if (node.val < target) return node.val; // found the next lowest
cur = node.left;
}
return null;
}
答案 0 :(得分:1)
private static TreeNode findNextLowest(TreeNode root, int target){
TreeNode node = root;
TreeNode res = null;
while(node != null){
while(node != null && node.val >= target){
node = node.left;
}
while(node != null && node.val < target){
res = node;
node = node.right;
}
}
return res;
}
答案 1 :(得分:-1)
不,因为你还没有实现 B inary S earch T ree,只是一棵二叉树。
BST会限制其值left.val
&lt; val
&lt; right.val
,所以你可以做到
// run time O(log(n)) if cur is balanced
public static Integer findNextLowest(TreeNode cur, int target) {
if (target < cur.val) { return cur.left != null ? findNextLowest(cur.left, target) : null; }
if (curr.right != null)
{
Integer result = findNextLowest(cur.right, target);
if (result != null) { return result; }
}
return cur.val;
}
你应该使用像R-B tree这样的东西来确保它是平衡的