Lowest Common Ancestor of a Binary Tree(递归法)

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

/**
 * 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 || p == root || q == root) 
            return root;
        TreeNode *left = lowestCommonAncestor(root->left, p, q);
        TreeNode *right = lowestCommonAncestor(root->right, p , q);
        if (left && right) 
            return root;
        return left ? left : right;
    }
};

方法二:

/**
 * 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 || p == root || q == root) 
            return root;
        TreeNode *leftnode = lowestCommonAncestor(root->left, p, q);
        TreeNode *rightnode = lowestCommonAncestor(root->right, p , q);
        if (!rightnode)
            return leftnode;
        if(!leftnode)
            return rightnode;
        return root;
    }
};

猜你喜欢

转载自blog.csdn.net/zrh_CSDN/article/details/81408520
今日推荐