标签:nan int roo || 递归调用 root struct node treenode
1.二叉搜索树
可以根据二叉搜树的性质进行搜索,实现步骤如下:
(1)判断root是否为空
(2)比较子节点p,q的大小,使得q为root的右节点;
(3)判断p,q节点是否为根节点,如果是则返回p(q);
(4)利用二叉搜索数的性质就你行递归调用
2.普通二叉树
实现步骤如下:
(1)首先判断根节点是否为空;
(2)判断p,q是否为根节点
(3)从左右子树进行递归调用
3.实现代码
//二叉搜索树 /** * 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; if(p->val > q->val) swap(p, q); if(roo->val == p->val || root->val == q->val){ return root->val == p->val ? p : q; } if(p->val < root->val && q->val > root->val) return root; if(root->val > q->val) return lowestCommonAncestor(root->left, p, q); return lowestCommonAncestor(root->right, p : q); } //普通二叉树 struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) { if(root == NULL) return NULL; if(root->val == p->val || root->val == q->val){ return root->val == p->val ? p : q; } struct TreeNode *temp1 = lowestCommonAncestor(root->left, p, q); struct TreeNode *temp2 = lowestCommonAncestor(root->right, p, q); if(temp1 == NULL && temp2 == NULL) return NULL; if(temp1 == NULl || temp2 == NULL){ return temp1 == NULL ? temp2 : temp2; } return root; }
标签:nan int roo || 递归调用 root struct node treenode
原文地址:https://www.cnblogs.com/spontanous/p/11770487.html