leetcode A1: Lowest Common Ancestor of a Binary Tree Part I
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);
} 
                    
                 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号