剑指offer题解68. 树中两个节点的最低公共祖先

剑指offer题解68. 树中两个节点的最低公共祖先 题目描述给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。题解/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val x; } * } */ 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); if(root.val p.val root.val q.val) return lowestCommonAncestor(root.right, p,q); return root; } }题目描述给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。题解/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val x; } * } */ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(rootnull || qroot || proot) return root; TreeNode left lowestCommonAncestor(root.left, p, q); TreeNode right lowestCommonAncestor(root.right, p, q); if(leftnull) return right; if(rightnull) return left; return root; } }