Middle-题目66:236. Lowest Common Ancestor of a Binary Tree

原创 2016年05月31日 16:35:44

题目原文:
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
题目大意:
寻找普通二叉树中两个节点的公共祖先。
题目分析:
看到了discuss中的一个极为巧妙的算法,先在左子树中找p或q,记为left,再到右子树中找,记为right,如果找到了(p或q都行),就把root往上传,没找到记为null,再判断返回的left和right哪个不是null,公共祖先就在哪里。
如果没有理解的话,看以下两种情况:
(1) p是q的祖先或者q是p的祖先,那么一定会搜索到root==p或root==q的情况,这样返回root,然后root的父节点上递归的两个函数一个为空一个为root,根据第5行则返回root,以此类推把root传到整个树的根节点。
(2) p和q分别位于某节点的左子树和右子树中,那么该节点上递归返回的left和right都不为空,第四行会返回这个root(即公共祖先),再依次往上传。
源码:(language:java)

public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == p || root == q || root == null) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left != null && right != null) return root;
        return left != null ? left : right;
    }
}

成绩:
13ms,beats 28.45%,众数13ms,45.40%
cmershen的碎碎念:
朴素解法是记录下p和q的路径,再求公共部分的最后一个节点,此解法的设计是基于p和q的第一次出现,既简洁又易于理解,堪称妙绝!

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

leetcode 236. Lowest Common Ancestor of a Binary Tree-二叉树共同祖先|深度遍历|递归|非递归

原题链接:236. Lowest Common Ancestor of a Binary Tree 【思路-Java】dfs|递归实现 本题是二叉树的深度遍历的典型应用,基础还是二叉树的遍历。 ...

LeetCode 236 Lowest Common Ancestor of a Binary Tree (LCA)

LeetCode 236 Lowest Common Ancestor of a Binary Tree (LCA)

leetcode 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. Accordin...

[leetcode] 236. Lowest Common Ancestor of a Binary Tree 解题报告

题目链接:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/    Given a binary tree...

LeetCode 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.Accord...

Leetcode 236. Lowest Common Ancestor of a Binary Tree

Leetcode 236. Lowest Common Ancestor of a Binary Treesource url题目描述Given a binary tree, find the low...

[Leetcode] 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. ...

算法分析与设计第六周:236. Lowest Common Ancestor of a Binary Tree

class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q...

Lowest Common Ancestor of a Binary Tree leetcode236

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.According ...

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. Accord...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Middle-题目66:236. Lowest Common Ancestor of a Binary Tree
举报原因:
原因补充:

(最多只允许输入30个字)