1. 程式人生 > >find second maximum element in Binary search tree

find second maximum element in Binary search tree

roo arc 一個 gpo sharp div find serial val

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