leetcode 236 Lowest Common Ancestor of a Binary Tree

来源:互联网 发布:减肥不减胸 知乎 编辑:程序博客网 时间:2024/05/21 17:13
/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {        if(!root||root==p||root==q)        {            return root;        }        TreeNode* left=lowestCommonAncestor(root->left,p,q);        TreeNode* right=lowestCommonAncestor(root->right,p,q);        if(left&&right)        {            return root;        }        else        {            return left==NULL?right:left;        }    }};

原创粉丝点击