1
+
2
+ [#0236-lowest-common-ancestor-of-a-binary-tree]
1
3
= 236. Lowest Common Ancestor of a Binary Tree
2
4
3
5
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/[LeetCode - Lowest Common Ancestor of a Binary Tree]
@@ -8,9 +10,7 @@ D瓜哥的思路:先找出一条从根节点到某个节点的路径;然后
8
10
9
11
思考题:如何按照"路径"的思路实现一遍?
10
12
11
- == 参考资料
12
-
13
- . https://en.wikipedia.org/wiki/Lowest_common_ancestor[Lowest common ancestor - Wikipedia]
13
+ == 解题分析
14
14
15
15
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
16
16
@@ -47,7 +47,60 @@ image::https://assets.leetcode.com/uploads/2018/12/14/binarytree.png[]
47
47
* All of the nodes' values will be unique.
48
48
* p and q are different and both values will exist in the binary tree.
49
49
50
+ == 思路分析
51
+
52
+ 这道题是 xref:0235-lowest-common-ancestor-of-a-binary-search-tree.adoc[235. Lowest Common Ancestor of a Binary Search Tree] 的延伸。但是,解题思路略有不同,本体的解题思路也可用于前者。
53
+
54
+ 有两种情况:
55
+
56
+ . 两个节点是一个树下的两个节点;
57
+ . 一个节点就是另外一个节点的祖先节点;
58
+
59
+ 根据这两点,针对一棵树进行递归遍历,去寻找当前节点与两个指定节点相等的节点,找到就返回当前节点(也就是两个节点其中之一),找不到就返回 `null`。
60
+
61
+ 当左右子树都返回不为 `null` 时,那么当前节点就是两棵树的公共祖先节点。情况如下:
62
+
63
+ image::images/0236-19.png[]
64
+
65
+
66
+
67
+ image::images/0236-00.png[]
68
+
69
+ image::images/0236-01.png[]
70
+
71
+ image::images/0236-02.png[]
72
+
73
+ image::images/0236-03.png[]
74
+
75
+ image::images/0236-04.png[]
76
+
77
+ image::images/0236-05.png[]
78
+
79
+ image::images/0236-06.png[]
50
80
81
+ image::images/0236-07.png[]
82
+
83
+ image::images/0236-08.png[]
84
+
85
+ image::images/0236-09.png[]
86
+
87
+ image::images/0236-10.png[]
88
+
89
+ image::images/0236-11.png[]
90
+
91
+ image::images/0236-12.png[]
92
+
93
+ image::images/0236-13.png[]
94
+
95
+ image::images/0236-14.png[]
96
+
97
+ image::images/0236-15.png[]
98
+
99
+ image::images/0236-16.png[]
100
+
101
+ image::images/0236-17.png[]
102
+
103
+ image::images/0236-18.png[]
51
104
52
105
53
106
[[src-0236]]
@@ -56,3 +109,15 @@ image::https://assets.leetcode.com/uploads/2018/12/14/binarytree.png[]
56
109
include::{sourcedir}/_0236_LowestCommonAncestorOfABinaryTree.java[]
57
110
----
58
111
112
+ [{java_src_attr}]
113
+ ----
114
+ include::{sourcedir}/_0236_LowestCommonAncestorOfABinaryTree_2.java[]
115
+ ----
116
+
117
+ == 参考资料
118
+
119
+ . https://en.wikipedia.org/wiki/Lowest_common_ancestor[Lowest common ancestor - Wikipedia]
120
+ . https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/solutions/238552/er-cha-shu-de-zui-jin-gong-gong-zu-xian-by-leetc-2/[236. 二叉树的最近公共祖先 - 官方题解^]
121
+ . https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/solutions/240096/236-er-cha-shu-de-zui-jin-gong-gong-zu-xian-hou-xu/[236. 二叉树的最近公共祖先 - DFS ,清晰图解^]
122
+ . https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/solutions/2023872/fen-lei-tao-lun-luan-ru-ma-yi-ge-shi-pin-2r95/[236. 二叉树的最近公共祖先 - 本题最简单写法!^]
123
+
0 commit comments