lletcode-236. Lowest Common Ancestor of a Binary Tree

来源:互联网 发布:中国网络安全法 编辑:程序博客网 时间:2024/06/08 01:11

解题思路:在根节点左右两侧寻找输入的两节点,一旦发现就返回其根节点的值.左右两子树返回均不空则表明根节点是要找的节点,只有一个不为空则表明待寻找的两子节点在一个根节点左边或右边的一侧.


代码实现:


class Solution {public:    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {        if(root==NULL)            return root;                    if(root==p || root==q)            return root;                    TreeNode *leftres = lowestCommonAncestor(root->left,p,q);        TreeNode *rightres = lowestCommonAncestor(root->right,p,q);                if(leftres!=NULL && rightres!=NULL)            return root;                return leftres!=NULL ? leftres : rightres;                        }};


0 0
原创粉丝点击