求二叉树的两个节点的最近公用先祖

2015-07-12  本文已影响0人  令一

My first Leetcode code.

/**

* Definition for a binary tree node.

* struct TreeNode {

*    int val;

*    TreeNode *left;

*    TreeNode *right;

*    TreeNode(int x) : val(x), left(NULL), right(NULL) {}

* };

*/

#define max(val1, val2)  (val1 > val2 ? val1 : val2)

#define min(val1, val2)  (val1 < val2 ? val1 : val2)

class Solution {

public:

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {

if (root == nullptr || p == nullptr || q == nullptr ) return nullptr;

if (max(p->val, q->val) < root->val)

return lowestCommonAncestor(root->left, p, q);

else if (min(p->val, q->val) > root->val)

return lowestCommonAncestor(root->right, p, q);

else

return root;

}

};

上一篇 下一篇

猜你喜欢

热点阅读