236. 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).”
_______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 5and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
- 树中 find val 三种写法
- 前序
![]()
- 前序
![]()
- 后序:遍历二叉树中所有节点
![]()
- 前序
在find函数的后序位置,如果发现left和right都非空,就说明当前节点是LCA节点,即解决了第一种情况:
在find函数的前序位置,如果找到一个值为val1或val2的节点则直接返回,恰好解决了第二种情况:
因为题目说了p和q一定存在于二叉树中(这点很重要),所以即便我们遇到q就直接返回,根本没遍历到p,也依然可以断定p在q底下,q就是LCA节点。
/** * 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; // 前序遍历位置,一条绳上,找到 p\q 一定就是公共祖先,都不需要往下遍历。 if (root == p || root == q) { return root; } // 如果 pq 在树的左右两边。 TreeNode* left = lowestCommonAncestor(root->left,p,q); TreeNode* right = lowestCommonAncestor(root->right,p,q); // 都不为空,说明找到了祖先,否则继续去左右子树寻找 if (left != NULL && right != NULL) { return root; } else if (left != NULL) { return left; } else if (right != NULL) { return right; } return NULL; } };




浙公网安备 33010602011771号