剑指offer-树中两个节点的最低公共祖先
Posted Roni
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指offer-树中两个节点的最低公共祖先相关的知识,希望对你有一定的参考价值。
普通二叉树
/** * 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 == null || root == p || root == q) return root; TreeNode left = lowestCommonAncestor(root.left,p,q); TreeNode right = lowestCommonAncestor(root.right,p,q); return left==null ? right : right==null ? left : root; } }
BST平衡二叉树
/** * 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 == null) return root; if(p.val < root.val && q.val < root.val) return lowestCommonAncestor(root.left,p,q); if(p.val > root.val && q.val > root.val) return lowestCommonAncestor(root.right,p,q); return root; } }
以上是关于剑指offer-树中两个节点的最低公共祖先的主要内容,如果未能解决你的问题,请参考以下文章
剑指Offer打卡day43—— ACWing 88. 树中两个结点的最低公共祖先
寻找二叉树中的最低公共祖先结点----LCA(Lowest Common Ancestor )问题(递归)