236. Lowest Common Ancestor of a Binary Tree

来源:互联网 发布:linux 日志切割脚本 编辑:程序博客网 时间:2024/06/03 20:20

寻找最低共同父节点(LCA)

代码如下:

public 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);        if (left != null && right != null){ //one in left, one in right            return root;        }else if (left != null && right == null){ //both in the left            return left;        }else if (left == null && right != null){ //both in the right            return right;        }else             return null;    }}

解释:
lowestCommonAncestor用来检查某个subtree是否包含p和q其中的至少1个

0 0
原创粉丝点击