236 Lowest Common Ancestor of a Binary Tree
2015-07-24 22:01
281 查看
题目链接:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
题目:
解题思路:
前序遍历二叉树,查找p和q。
一旦找到某一节点,就将其返回,不再遍历其子树。
若某一子树遍历完后都没有找到p或q,则返回null。
每一次递归完成后,比较当前根节点的左右子树是否找到p或q。
若左右子树都找到了(p和q分别在左子树和右子树中),返回当前根节点。
若只有一个子树找到了,另一子树返回为空(p和q都在同一子树中),返回不为空的子树节点(不一定是当前根节点的子树根节点)。
若两个子树都没找到(p和q都不在该子树中),返回左子树(实则返回null)。
题目:
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 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
解题思路:
前序遍历二叉树,查找p和q。
一旦找到某一节点,就将其返回,不再遍历其子树。
若某一子树遍历完后都没有找到p或q,则返回null。
每一次递归完成后,比较当前根节点的左右子树是否找到p或q。
若左右子树都找到了(p和q分别在左子树和右子树中),返回当前根节点。
若只有一个子树找到了,另一子树返回为空(p和q都在同一子树中),返回不为空的子树节点(不一定是当前根节点的子树根节点)。
若两个子树都没找到(p和q都不在该子树中),返回左子树(实则返回null)。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root == p || root == q) return root; TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); return left == null ? right : right == null ? left : root; } }
相关文章推荐
- 数据库设计的细节说明
- centos6.6下安装GreenPlum4.3.5.2
- 注解+
- Travel(HDU 4284状压dp)
- 同步调用,回调,异步调用
- socket阻塞与非阻塞,同步与异步、I/O模型
- LeetCode 之Edit Distance
- 在64位操作系统上使用FlashDevelop的Debug功能
- 阿里云服务器ubuntu创建SVN版本控制服务器
- 常用命令合集
- 让你提前知道软件开发(45):第一印象的代码
- 棋盘覆盖(大数阶乘,大数相除)
- 把Scheme翻译成Java和C++的工具
- [leetcode]Search for a Range
- [LeetCode]Maximum Product Subarray
- c语言文件操作详解
- Java利用POI导入导出Excel中的数据
- 基于Linux的智能家居的设计(1)
- [leedcode 128] Longest Consecutive Sequence
- linux配置java环境变量(详细)