当前位置:诺佳网 > 电子/半导体 > 区块链 >

LeetCode 236 最近公共祖先 Lowest Common Ancestor of a B

时间:2018-01-24 | 栏目:区块链 | 点击:

题目:找p和q的最近公共祖先
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

_______3______ / \ ___5__ ___1__ / \ / \ 6 _2 0 8 / \ 7 4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
理解:

当遍历到一个root点的时候,

1.判断root是不是null如果root为null,那么就无所谓祖先节点,直接返回null就好了

2.如果root的左子树存在p,右子树存在q,那么root肯定就是最近祖先

3.如果pq都在root的左子树,那么就需要递归root的左子树,右子树同理

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(root == NULL || 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; } }

您可能感兴趣的文章:

相关文章