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的主要内容,如果未能解决你的问题,请参考以下文章

30秒运行超时的错误(Maximum execution time of 30 seconds exceeded)

php 超时 解决办法 (Maximum execution time of 30 seconds exceeded)这个问题?

MySQL server has gone away和Maximum execution time of 120 seconds exceeded

虚拟主机出错Fatal error: Maximum execution time of 30 seconds exceeded in

Find the maximum(规律,大数)

请教各位,dedecms使用wamp进入后台点击没反应,提示Fatal error: Maximum execution time of 30 seconds