博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]236. Lowest Common Ancestor of a Binary Tree
阅读量:2785 次
发布时间:2019-05-13

本文共 540 字,大约阅读时间需要 1 分钟。

找出两个节点的公共祖先,树是普通二叉树

lowestCommonAncestor找在root为根节点的子树上遍历到的第一个p或者q,如果两个都遍历到就返回root,如果p和q都不在这个子树上就返回null,否则返回p和q里面先遍历到的那个。因此如果left和right都不是null,那么就返回root

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;    }}

转载地址:http://hahld.baihongyu.com/

你可能感兴趣的文章
Golang入门教程(二)Ubuntu16.04下安装golang(实例:Golang 定时任务管理器)
查看>>
Lua程序设计(二)面向对象概念介绍
查看>>
Nginx ab压力测试
查看>>
JAVA -- NPOI在excel中画直线
查看>>
JAVA -- 小结
查看>>
JAVA -- 在页面中得到地址栏中参数的值并传递
查看>>
JAVA -- POI导出excel
查看>>
JAVA -- Java compiler level does not match the version of the installed Java project facet.
查看>>
JAVA -- ant编译时出现Compile failed; see the compiler error output for details异常
查看>>
WEB前端 -- 读取下拉框中的text、value
查看>>
JAVA -- 获取时间
查看>>
PowerDesigner初用问题解决
查看>>
网络知识 -- TCP连接实例
查看>>
Oracle -- like、instr()、substr()
查看>>
UIWindow
查看>>
GCDAsyncSocket类库,IOS下TCP通讯使用心得
查看>>
block使用小结、使用block、如何防止循环引用
查看>>
程序员高效率工作工具推荐(必备工具)
查看>>
iOS多线程编程之NSThread的使用
查看>>
使用Xcode和Instruments调试解决iOS内存泄露
查看>>