4.7 first common ancestor

Design an algorithm and write code to find the first common ancestor of two nodes
in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not
necessarily a binary search tree.

解法1: recursively


public boolean isCover(TreeNode node, TreeNode t){

    if(node==t) return true;
    if(node==null) return false;
    return isCover(node.left,t)|| isCover(node.right, t);
}


public TreeNode helper(TreeNode root, TreeNode p, TreeNode q){
    if(root==null) return null;
    if(root==p||root==q) return root; //important
        
    boolean is_left_p = isCover(root.left, p);
    boolean is_left_q = isCover(root.left, q);
    if(is_left_q!=is_left_p) return root;
    TreeNode child_side = is_left_p? node.left;node.right;
    
    return helper(child_side, p, q);
}


public Node main(Node root, Node p, Node q){
    if(!isCover(root,p))||!isCover(root,q)) return null;
    return helper(root, p, q);

}


书中分析:This algorithm runsinO(n) time on a balanced tree.This is because covers is called on
2n nodes in the first call (n nodes for the left side, and n nodes for the right side). After
that, the algorithm branches left or right, at which point covers will be called on 2n/2
nodes, then 2n/4, and so on.This results in a runtime of 0(n).



解法2 冒泡



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值