ツリー内の任意の2つのノードの最も低い共通の祖先ノードを返します.

2239 ワード

/** * 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) { int bigOne = 0; int smallOne = 0; if(p->val < q->val){ bigOne = q->val; smallOne = p->val; } else{ bigOne = p->val; smallOne = q->val; } TreeNode *lowestCommonAncestor = root; while(true){ if (lowestCommonAncestor->val < smallOne){ lowestCommonAncestor = lowestCommonAncestor->right; } else if (lowestCommonAncestor->val > bigOne){ lowestCommonAncestor = lowestCommonAncestor->left; } else{ return lowestCommonAncestor; } } } };