最近公共祖先

来源:互联网 发布:淘宝品牌男装店 编辑:程序博客网 时间:2024/06/05 21:18

给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。

最近公共祖先是两个节点的公共的祖先节点且具有最大深度。


点题:从下而上,第一次两边都有

/** * Definition of TreeNode: * class TreeNode { * public: *     int val; *     TreeNode *left, *right; *     TreeNode(int val) { *         this->val = val; *         this->left = this->right = NULL; *     } * } */class Solution {public:    /*     * @param root: The root of the binary search tree.     * @param A: A TreeNode in a Binary.     * @param B: A TreeNode in a Binary.     * @return: Return the least common ancestor(LCA) of the two nodes.     */    TreeNode * lowestCommonAncestor(TreeNode * root, TreeNode * A, TreeNode * B) {        // find target node OR null node        if (root == NULL || root->val == A->val || root->val == B->val) {            return root;        }        // find children nodes        TreeNode* left = lowestCommonAncestor(root->left, A, B);        TreeNode* right = lowestCommonAncestor(root->right, A, B);        if (left != NULL && right != NULL) {            return root;        }        // return find results        return left == NULL? right : left;    }};


原创粉丝点击