建立局域网网站,wordpress comments 时间为什么是utc时间,网站org免费注册,大学生电子商务策划书题目#xff1a;
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为#xff1a;“对于有根树 T 的两个节点 p、q#xff0c;最近公共祖先表示为一个节点 x#xff0c;满足 x 是 p、q 的祖先且 x 的深度尽可能大#xff08;一个…题目
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为“对于有根树 T 的两个节点 p、q最近公共祖先表示为一个节点 x满足 x 是 p、q 的祖先且 x 的深度尽可能大一个节点也可以是它自己的祖先。 可以使用递归的方式来解决这个问题。递归函数的基本思路是: 如果当前节点为空,返回null如果当前节点就是其中一个目标节点,返回当前节点分别在左子树和右子树中查找目标节点如果左右子树都找到了目标节点,说明当前节点就是最近公共祖先,返回当前节点如果只在左子树找到了一个目标节点,返回左子树的结果如果只在右子树找到了一个目标节点,返回右子树的结果 这个leetcode官方题解下面的树很正确的具象化了这个题的任务。
下面附上代码
public class no_236 {public static void main(String[] args) {Integer[] input {3, 5, 1, 6, 2, 0, 8, null, null, 7, 4};TreeNode root TreeNode.buildTree(input);int p 5, q 1;TreeNode treeNode lowestCommonAncestor(root, root.left, root.right);System.out.println(treeNode.val);}public static 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;}if (left ! null) {return left;}if (right ! null) {return right;}return null;}
}