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); }
相关文章推荐
- leetcode A1: Lowest Common Ancestor of a Binary Tree Part I
- [LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree
- leetcode 236 Lowest Common Ancestor of a Binary Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode 之 Lowest Common Ancestor of a Binary Search Tree
- leetcode: (235) Lowest Common Ancestor of a Binary Search Tree
- leetcode 235: Lowest Common Ancestor of a Binary Search Tree
- 【LeetCode 235】Lowest Common Ancestor of a Binary Search Tree
- LeetCode235. Lowest Common Ancestor of a Binary Search Tree
- [LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode 236. Lowest Common Ancestor of a Binary Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- 72【leetcode】经典算法- Lowest Common Ancestor of a Binary Search Tree(lct of bst)
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树
- [LeetCode]236. Lowest Common Ancestor of a Binary Tree
- 72【leetcode】经典算法- Lowest Common Ancestor of a Binary Search Tree(lct of bst)
- [LeetCode]: 235:Lowest Common Ancestor of a Binary Search Tree
- [Leetcode] Lowest Common Ancestor of a Binary Tree 最小公共祖先
- Lowest Common Ancestor of a Binary Tree Part I
- 【Leetcode】Lowest Common Ancestor of a Binary Search Tree