236. 二叉树的最近公共祖先 - 力扣(LeetCode)

- // 后续遍历是天然的回溯:从树的底层向上寻找
- var lowestCommonAncestor = function (root, p, q) {
- // 使用递归的方法
- // 需要从下到上,所以使用后序遍历
- // 1. 确定递归的函数
- const travelTree = function (root, p, q) {
- // 2. 确定递归终止条件
- if (root === null || root === p || root === q) {
- return root;
- }
- // 3. 确定递归单层逻辑
- let left = travelTree(root.left, p, q);
- let right = travelTree(root.right, p, q);
- if (left != null && right != null) return root;
- if (left == null && right != null) {
- return right;
- } else if (left != null && right == null) {
- return left;
- } else { // (left == null && right == null)
- return null;
- }
- }
- return travelTree(root, p, q);
- };
235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)

- var lowestCommonAncestor = function(root, p, q) {
- if(root === null) return root;
- if(root.val > p.val && root.val > q.val) {
- let left = lowestCommonAncestor(root.left, p, q);
- if(left!==null) {
- return left;
- }
- }
- if(root.val < p.val && root.val < q.val) {
- let right = lowestCommonAncestor(root.right, p, q);
- if(right!==null) {
- return right;
- }
- }
- return root;
- };