[抄题]:

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

“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.

[思维问题]:

不知道子节点怎么用dc。直接对给出的p,q节点进行操作即可。

[一句话思路]:

左右分开 谁不空返回谁

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

(left != null && right != null) 时,返回的是root节点的结果,不需要再做递归运算了。是一个“合”的过程。

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[总结]:

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构,为什么不用别的数据结构]:

只有dc算法,没有数据结构

[其他解法]:

自己写traverse函数:不好,会形成全局变量

[Follow Up]:

有parent指针的:用对齐的方法做

[LC给出的题目变变变]:

Lowest Common Ancestor of a Binary Search Tree 一模一样的,约束条件没用,直接套。

public class Solution {
/*
* @param root: The root of the binary search tree.
* @param A: A TreeNode in a Binary.
* @param B: A TreeNode in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
if (root == null || A == root || B == root) {//
return root;
}
//divide
TreeNode left = lowestCommonAncestor(root.left, A, B);
TreeNode right = lowestCommonAncestor(root.right, A, B); //conquer
if (left != null && right != null) {
return root;//
}
else if (left != null) {
return left;
}
else if (right != null) {
return right;
}
else {
return null;
}
}
}

最新文章

  1. XAML parser exception
  2. 加载json文件没显示图片
  3. Android--自动搜索提示
  4. ID
  5. inand和emmc区别
  6. 几种C#实现播放声音的方法
  7. 网易DBA私享会分享会笔记1
  8. TextMesh Pro SpriteAsset Load From Assetbundle
  9. selenium webdriver——设置元素等待
  10. redis 系列21 复制Replication (上)
  11. Python_day9
  12. 有时候eclipse 导入maven项目 启动的时候回出现这样一个问题
  13. java io系列05之 ObjectInputStream 和 ObjectOutputStream
  14. SAS LOGISTIC 逻辑回归中加(EVENT='1')和不加(EVENT='1')区别
  15. Shiro HashedCredentialsMatcher 认证匹配
  16. Python3学习笔记11-循环语句
  17. node.js 初学(一)—— http fs 服务器/文件/post get
  18. R子集subset
  19. Java - Float与Double类型比较
  20. 06_zookeeper_原生API使用2

热门文章

  1. PHP中的urlencode,rawurlencode和JS中的encodeURI,encodeURIComponent
  2. 团队作业(二):ASB
  3. TensorFlow函数:tf.FIFOQueue队列
  4. reduce|sum
  5. java中的URLConnection和HttpURLConnection有什么区别(因为我自己搜到别人写的区别看下来都没有什么区别)
  6. Java笔试基础01
  7. opencv查看源代码
  8. delphi 泛型 c++builder 泛型
  9. 机器学习入门-贝叶斯构造LDA主题模型,构造word2vec 1.gensim.corpora.Dictionary(构造映射字典) 2.dictionary.doc2vec(做映射) 3.gensim.model.ldamodel.LdaModel(构建主题模型)4lda.print_topics(打印主题).
  10. spring事务没回滚