给一棵BST,注意,BST的value是一个private的东西,我们拿不到。我啥也不想说了,这题面试没写好,真得挺不开心的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
class { Node left; Node right; }
public Node nextLargest(Node node, Node root) { if (root == null || node == null) return null; Node ans = null; if (node.right != null) { node = node.right; while (node.left != null) { node = node.left; } return node; } Stack<Node> s = new Stack<>(); while (root != null) { s.push(root); root = root.left; } while (!s.isEmpty()) { Node cur = s.pop(); Node right = cur.right; while (right != null) { s.push(right); right = right.left; } if (cur == node) { ans = s.isEmpty() ? null : s.pop(); break; } } return ans; }
|
近期评论