二叉树 的 最近公共祖先

版权声明:be the one ~you will be the one~~ https://blog.csdn.net/Hqxcsdn/article/details/87924236

在这里插入图片描述

答题思路还是运用递归
当一个节点满足特定条件时,函数会跳出,不然一直递归,直到为null
如果 遍历的左右节点都不为空,说明一个在左子树,一个在右子树 ,则root必为其公共父节点
如果 只有 左不为空,说明 都在左子树,则该left节点必为 公共父节点 同理 右节点

/**
 * 
 */

/***
 * @author 18071
 * @Date 2019年2月25日
 * 功能:给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
 ***/
public class test {
    public static void main(String args[]) {
    	TreeNode t=new TreeNode(3);
    	TreeNode p=t.left=new TreeNode(5);
    	t.left.left=new TreeNode(6);
    	t.left.right=new TreeNode(2);
        t.left.right.left=new TreeNode(7);
        t.left.right.left=new TreeNode(4);
        TreeNode q= t.right=new TreeNode(1);
        t.right.left=new TreeNode(0);
        t.right.right=new TreeNode(8);
        
      System.out.println(find(t,p,q).val);
    }
	
   
    public static TreeNode find(TreeNode tn , TreeNode p,TreeNode q) {
    	if(tn==null) {
    		return null;
    	}
    	else if((tn.left==p&&tn.right==q)|| (tn.left==q&&tn.right==p)||tn==p||tn==q) {
    		return tn;
    		
    	}
    	TreeNode left=find(tn.left,p,q);
    	TreeNode right=find(tn.right,p,q);
    	if(right !=null&&left!=null) {
    		return tn;
    	}
    	if(right!=null) {
    		return tn.right;
    		
    	}
    	if(left!=null ) {
    		return tn.left;
    	}
		return null;
    	
    }
	
}


 class TreeNode {
	      int val;
	      TreeNode left;
	      TreeNode right;
	      TreeNode(int x) { val = x; }
	 }

猜你喜欢

转载自blog.csdn.net/Hqxcsdn/article/details/87924236