Code & Func
2017-11-07

第42天。

今天的题目是Lowest Common Ancestor of a Binary Tree:

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).”

1
_______3______
2
/ \
3
___5__ ___1__
4
/ \ / \
5
6 _2 0 8
6
/ \
7
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.

额,怎么说呢。好久没有在上课前就AC掉了呢。

恩,题目的意思是,找最近的公共祖先。

考虑根节点,如果不考虑特殊的情况(比如说只用一个节点或干脆就没有节点),那么如果我们对其左子树和右子树递归的调用lowestCommonAncestor,那么其返回值就有以下几种情况:

  • leftright都非空,那么说明root节点就是lowestCommonAncestor,那我们就返回root
  • 只有left非空,那么说明lowestCommonAncestor在左子树中,那么我们就返回left
  • 只有right非空,与上面类似,我们就直接返回right
  • 两个都是空,说明pq都不在这棵子树中,那其lowestCommonAncestor就是nullptr.

然后我们再考虑一下特殊情况:

  • rootnullptr,那么就说明到了最底部了,直接返回nullptr即可
  • rootpq相等,说明我们找到了其一个祖先,则返回pq.

然后将上面的思路写出来就是:

1
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
2
if (root == nullptr || root == p || root == q) return root;
3
4
TreeNode *left = lowestCommonAncestor(root->left,p,q);
5
TreeNode *right = lowestCommonAncestor(root->right,p,q);
6
7
if (left && right) return root;
8
else if (left) return left;
9
else if (right) return right;
10
else return nullptr;
11
12
}

其实上面有一个问题没考虑到,要是只有p在这棵子树中,而q不在,那怎么办。

emmmm,但是上面的解法是过了测试的。

如果要考虑这个问题的话,上面就有一些假设就是错的了,因为在lowestCommonAncestor在某些情况返回非空只是说明,这棵子树中有一个节点是与pq相同的。

上一条动态