LeetCode 236. Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.


The problem will get interesting if the tree node has parent node. (....need to be continued)


TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root) return NULL;
        if(root == p || root == q) return root;
        TreeNode* tmp_1 = lowestCommonAncestor(root->left, p, q);
        TreeNode* tmp_2 = lowestCommonAncestor(root->right, p, q);
        if(tmp_1 && tmp_2) return root;
        return tmp_1 ? tmp_1 : tmp_2;
    }

Or, if given the TreeNode has a parent pointer.

class TreeNode {
  int val;
  TreeNode* left;
  TreeNode* right;
  TreeNoe* parent;
};

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  if(!root) return NULL;
  unordered_set<TreeNode*> nodes;
  while(p || q) {
    if(p) {
      if(!nodes.insert(p).second) return p;
      p = p->parent;
    }
    if(q) {
      if(!nodes.insert(q).second) return q;
      q = q->parent;
    }
  }
  return NULL;
}


One more variation:

/*
  Give a tree, find the smallest substree that contains all the tree's deepest nodes.
      a
    /   \
    b   d
   /\   |
   e f  g
  / / \
 h i   j
*/
/*
  depth of tree: 4
  deepest nodes: [h, i, j]
  least common ancestor of [h, i, j] : b
  return b.
*/
int getDepth(TreeNode* root) {
  if(!root) return 0;
  return 1 + max(getDepth(root->left), getDepth(root->right));
}

void findCommnNode(TreeNode* root, TreeNode* a, TreeNode* b) {

}


TreeNode* leastCommonAncestor(TreeNode* root) {  // pseudo-code
  int depth = getDepth(root);
  vector<TreeNode*> leaves = TreeLeaves(root, depth);
  if(leaves.size() == 1) return root;
  TreeNode* commonNode = leaves[0];
  for(int i = 1; i < leaves.size(); ++i) {
    findCommonNode(root, leaves[i], commonNode);
    if(commonNode == root) break;
  }
  return commonNode;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值