码迷,mamicode.com
首页 > 其他好文 > 详细

find second maximum element in Binary search tree

时间:2017-12-14 03:46:57      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:遍历   iter   class   sea   ati   sha   second   bin   blog   

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

标签:遍历   iter   class   sea   ati   sha   second   bin   blog   

原文地址:http://www.cnblogs.com/apanda009/p/8035610.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!