您的位置:首页 > 其它

leetcode A1: Lowest Common Ancestor of a Binary Tree Part I

2013-01-31 16:51 459 查看


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



_______3______
/              \
___5__          ___1__
/      \        /      \
6      _2       0       8
/  \
7   4


If you are not so sure about the definition of lowest common ancestor (LCA), please refer to my previous post:Lowest
Common Ancestor of a Binary Search Tree (BST) or the definition of LCA here.
Using the tree above as an example, the LCA of nodes 5 and 1 is 3.
Please note that LCA for nodes 5 and 4 is 5.

Hint:

Top-down or bottom-up? Consider both approaches and see which one is more efficient.

#include <iostream>
#include <vector>
#include <set>
#include <cmath>
#include <fstream>

using namespace std;
class TreeNode{
public:
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x),left(NULL),right(NULL) {};
};

TreeNode* commonAncestor( TreeNode* root, TreeNode* t1, TreeNode* t2) {
if(root==NULL) return NULL;

TreeNode* l = commonAncestor(root->left, t1, t2);
TreeNode* r = commonAncestor(root->right, t1, t2);
if( l && r ) {
return root;
}
return l ? l : r;
}

void main(int argc, char** argv)
{
commonAncestor(root, t1, t2);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: