LeetCode_Lowest Common Ancestor of a Binary Search Tree (Binary Tree)
Posted brucemengbm
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode_Lowest Common Ancestor of a Binary Search Tree (Binary Tree)相关的知识,希望对你有一定的参考价值。
Lowest Common Ancestor of a Binary Search Tree
一、题目描写叙述
二、思路及代码
二叉搜索树有个性质:左子树的值都比根节点小,右子树的值比根节点大。那么我们的思路就是递归比較。
假设输入的两个节点的值比当前节点小,说明是在当前根节点的左子树中;反之则在右子树中。
假设当前根节点比一个大。比一个小。那么第一个出现的这种节点就是近期的父亲节点了。
/**
* 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.val > p.val && root.val > q.val){
return lowestCommonAncestor(root.left, p, q);
}else if(root.val < p.val && root.val < q.val){
return lowestCommonAncestor(root.right, p, q);
}else{
return root;
}
}
}
Lowest Common Ancestor of a Binary Tree
一、题目描写叙述
二、思路及代码
假设是普通的二叉树。没有了二叉搜索树的特性。就要遍历;于是我们用到DFS遍历树
/**
* 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; //找到p或者q节点,或者到最底层的叶子节点时,返回;
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; //所以假设都未找到,返回null
}
}
以上是关于LeetCode_Lowest Common Ancestor of a Binary Search Tree (Binary Tree)的主要内容,如果未能解决你的问题,请参考以下文章
ByteArraySerializer is not an instance of org.apache.kafka.common.serialization.Serializer
appium启动服务,链接app报错elenium.common.exceptions.WebDriverException: Message: An unknown server-side erro
ALG 2-4: A Survey of Common Running Times (对常见运行时间的分析)
错误记录Android Studio 编译报错 ( Module was compiled with an incompatible version of Kotlin. The binary )