Lowest Common Ancestor of a Binary Tree

来源:互联网 发布:网络配线架品牌 编辑:程序博客网 时间:2024/06/06 14:17

思路为:

找到p,q,的节点,利用递归从而找到p,q的共公父节点,返回的父节点即为所求的节点

 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {        if(root== null) return null;if(root==p) return root;else if(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;else{return left==null?right:left;}    }


0 0