find second maximum element in Binary search tree

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了find second maximum element in Binary search tree相关的知识,希望对你有一定的参考价值。

一个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;
    }

  

以上是关于find second maximum element in Binary search tree的主要内容,如果未能解决你的问题,请参考以下文章