Title Address: Click to open the link
Solution one: For a case that is too deep.
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL) , right (NULL) {}}; */class Solution {public:treenode* lowestcommonancestor (treenode* root, treenode* p, treenode* q) {if (Root==NU LL) return NULL; P1=p; p2=q; DFS (root,1); while (num1!=num2) {if (num1>num2) num1=num1>>1; else num2=num2>>1; } ansnum=num1; GetNode (root,1); return ansnode; }private:int Num1,num2,ansnum; TreeNode *p1,*p2,*ansnode; void Dfs (TreeNode *root,int num) {if (root) {if (ROOT==P1) num1=num; if (ROOT==P2) num2=num; DFS (Root->left,2*num); DFS (ROOT->RIGHT,2*NUM+1); }} void GetNode (TreeNode *root,int num) {if (root) {if (num==ansnum) ansnode=root; GetNode (Root->left,2*num); GetNode (root->RIGHT,2*NUM+1); } }};
Solution Two: All can be over.
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL) , right (NULL) {}}; */class Solution {public: treenode* lowestcommonancestor (treenode* root, treenode* p, treenode* q) { ans=null;< C6/>dfs (root,p,q); return ans; } Private: TreeNode *ans; treenode* dfs (TreeNode *root,treenode *p,treenode *q) { if (root&&ans==null) { treenode* P1=dfs ( ROOT->LEFT,P,Q); treenode* P2=dfs (root->right,p,q); BOOL X=false,y=false; if (root==p| | p1==p| | p2==p) x=true; if (root==q| | p1==q| | P2==Q) y=true; if (x&&y) { ans=root; return NULL; } if (x) return p; if (y) return q; return NULL; } return NULL; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Lowest Common Ancestor of a Binary Tree