一个BST, 问怎么找到第二大的节点。首先说了个naive的方法,serialize, 他问有没有更有效的方法。最后用的iterative的方法向右遍历子节点 log(n)
或者inorder, O(n):
public int find(TreeNode root) { TreeNode first = root; TreeNode second = null; while (root != null) { if (root.right == null && root.left == null) { return second.val; } else if (root.right != null) { second = first; first = root.right; root = root.right; } else if (root.left != null) { root = root.left; break; } } while (root != null) { if (root.right == null) { return root.val; } else { root = root.right; } } return -1; }
时间: 2024-11-17 18:15:07