235. 二叉搜索树的最近公共祖先
Posted yuhong1103
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了235. 二叉搜索树的最近公共祖先相关的知识,希望对你有一定的参考价值。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution 11 { 12 public: 13 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 14 { 15 if(p == root || q == root || !root) return root; 16 17 TreeNode* a = lowestCommonAncestor(root->left,p,q); 18 TreeNode* b = lowestCommonAncestor(root->right,p,q); 19 if(!a && b) return b; 20 else if(a && !b) return a; 21 else if(a && b) return root; 22 else return NULL; 23 } 24 };
以上是关于235. 二叉搜索树的最近公共祖先的主要内容,如果未能解决你的问题,请参考以下文章