LeetCode Lowest Common Ancestor of a Binary Search Tree

来源:互联网 发布:高速公路机电系统优化 编辑:程序博客网 时间:2024/06/17 07:58
/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right; * }; */struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {    if(root==NULL)        return NULL;    else if(root->val<p->val&&root->val<q->val)        return lowestCommonAncestor(root->right,p,q);    else if(root->val>p->val&&root->val>q->val)        return lowestCommonAncestor(root->left,p,q);    else        return root;}


这个题是找两节点最近祖先节点,开始理解成找最近最小祖先节点打算用数组记录。

后发现题目含义之后,改用递归方法。

C语言 2016/2/13

0 0
原创粉丝点击