leetcode 236. Lowest Common Ancestor of a Binary Tree
Posted hwd9654
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 236. Lowest Common Ancestor of a Binary Tree相关的知识,希望对你有一定的参考价值。
看看什么是最低共同祖先,就是第一个左右分别存在p和q的节点
还是正常dfs,当遇到null返回null,遇到p返回p,遇到q返回q
若left 和 right 都不为null则说明这就是我们要找的节点
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); if(left != null && right != null) return root; return left == null ? right : left;
以上是关于leetcode 236. Lowest Common Ancestor of a Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 236: Lowest Common Ancestor of a Binary Tree
leetcode 236: Lowest Common Ancestor of a Binary Tree
leetcode236 Lowest Common Ancestor of a Binary Tree
leetcode236 - Lowest Common Ancestor of a Binary Tree - medium