Two ways of thinking about the nearest common ancestor of a binary tree

 

class Solution {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

        //Write a blog liangzhongsi

        //The first

        /*

        if(root == null) return null;

        if(root == p || root == q) return root;

        TreeNode leftTree = lowestCommonAncestor(root.left,p,q);

        TreeNode rightTree = lowestCommonAncestor(root.right,p,q);

        if(leftTree!=null && rightTree!=null) return root;

        else if(leftTree!=null) return leftTree;

        else return rightTree;

        */


 

     



 

        //The second type of linked list public node stack

        Stack stackP = new LinkedList();

        Stack stackQ = new LinkedList();

        getPath(root,p,stackP);

        getPath(root,q,stackQ);

        int sizeP = stackP.size();

        int sizeQ = stackQ.size();

       


 

    }


 

    private static boolean getPath (TreeNode root,TreeNode node ,Stack Stack){

        if(root == null) return false;

        if(root == node) return true;

        stack.push(root);

        boolean b1 = getPath(root.left,node,stack);

        if(b1 == true) return true;

        boolean b2 = getPath(root.right,node,stack);

        if(b2 == true) return true;

        if( b1==false && b2==false ) stack.pop();

        return false;

    }

}

Guess you like

Origin blog.csdn.net/m0_73381672/article/details/132267245