[Offer] [68] [two nodes of the tree lowest common ancestor]

Title Description

  Enter two tree nodes, they are seeking the lowest common ancestor.

[Cow brush off questions address network] No

Ideas analysis

  The question we must first determine whether a binary tree, but also to determine whether the binary search tree, if there is a parent pointer, or just plain binary tree.

  1. When the tree is a binary search tree, the lowest common ancestor node size between two tree node size.
  2. When the tree is a common tree traversal using information passed up the child nodes. In the left and right sub-tree to find out if there are two tree nodes, tree nodes if the two were about sub-tree, indicating that the root is their lowest common ancestor.

Test Case

  1. Functional Test: ordinary tree, tree left oblique and right oblique tree
  2. Special tests: null

Java code

public class Offer068 {
    public static void main(String[] args) {
        test1();
        test2();
        test3();
        
    }

    /*
     * 二叉搜索树
     * 利用大小关系即可
     */
    public TreeNode getLowestCommonParentBST(TreeNode root,TreeNode node1,TreeNode node2) {
        while(true) {
            if(root==null)
                return root;
            if(root.val<node1.val && root.val<node2.val)
                root=root.right;
            else if(root.val>node1.val && root.val>node2.val)
                root=root.left;
            else
                return root;
        }
    }
     
     
    /*
     * 普通二叉树
     * 将下面结点的信息利用递归s往上传递
     */
    public TreeNode getLowestCommonParent(TreeNode root,TreeNode node1,TreeNode node2) {
        if(root==null || root== node1 || root== node2)
            return root;
        TreeNode left=getLowestCommonParent(root.left, node1, node2);
        TreeNode right=getLowestCommonParent(root.right, node1, node2);
        return left==null? right:right==null? left:root;
    //  上面这句代码就是:
    //  if(left==null) {
//            return right;
    //  }else {
//        if(right==null)
//            return left;
//        else
//            return root;
    //  }
    }


    private static void test1() {

    }

    private static void test2() {

    }
    private static void test3() {

    }

}

Code link

Offer to prove safety codes -Java

Guess you like

Origin www.cnblogs.com/haoworld/p/offer68-shu-zhong-liang-ge-jie-dian-de-zui-di-gong.html