1. 程式人生 > >演算法:在二叉樹中尋找兩個節點的共同祖先

演算法:在二叉樹中尋找兩個節點的共同祖先

問題:已知二叉樹root和兩個節點p和q,要求找出p和q在root中的最早的共同祖先。要求:該二叉樹的節點沒有parent指標(如果有parent指標,演算法會簡單很多)。


演算法思想:中序訪問二叉樹,對於當前節點,當其左子樹和右子樹訪問完畢,且p與q都已經訪問過,則當前節點就是p與q的共同祖先。


演算法偽碼:

commonAncestor = null;

int inorder(node)
{
  if (node == null)
    return 0;

  if (commonAncesotr)  // found
    return 0;

  // 處理左子樹
  int left = inorder(node->l);

  // 處理當前節點
  int in = 0;
  if (node == p || node == q)
    in = 1;

  // 處理右子樹
  int right = inorder(node->r);
  
  int sum = left + in + right;

  // 左右子樹都處理完畢,當前節點也處理完畢。檢查sum,如果sum == 2,說明p和q都訪問過了,當前節點就是commonAncestor。
  if (sum == 2)
  {
      commonAncestor = node;
      return 0;
  }

  return sum;
}