剑指offer4-(LCA)Lowest Common Ancestor

题目可以参考leetcode,写完顺便可以用leetcode OJ测试一下自己代码的正确性。这一题不难,一般的递归思想就可以解决。但当时面试京东的时候,别人总说我遍历了两次,能否只遍历一次?后来看剑指offer的面试题39:二叉树的深度,解法中利用后序遍历有提到每个节点只遍历一次,所以基于此我把LCM列为剑指offer,以供参考。

/**
 * 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 == NULL)
        {
            return NULL;
        }
        if (root->val == p->val || root->val == q->val)
        {
            return root;
        }
        else
        {
            TreeNode* leftNode = lowestCommonAncestor(root->left, p, q);
            TreeNode* rightNode = lowestCommonAncestor(root->right, p, q);
            if (leftNode == NULL)
            {
                return rightNode;
            }
            if (rightNode == NULL)
            {
                return leftNode;
            }
            return root;
        }
    }
};

你可能感兴趣的:(C++)