数据结构复习------二叉树的堂兄弟节点

class Solution {
    public boolean isCousins(TreeNode root, int x, int y) {
        return depth(root,x)==depth(root,y)&&father(root,x)!=father(root,y);
    }

    int depth(TreeNode root,int x) {
    	if(root==null)
    		return -100;
    	else {
    		TreeNode L=root.left,R=root.right;
    		if(root.val==x)
    			return 1;
    		else
    			return Math.max(depth(L,x)+1, depth(R,x)+1);
    	}
    }
    
    TreeNode father(TreeNode root,int x) {
    	if(root==null)
    		return null;
    	else {
    		TreeNode L=root.left,R=root.right;
    		if((L!=null&&L.val==x)||(R!=null&&R.val==x))
    			return root;
    		else {
    			if(father(L,x)!=null)
    				return father(L,x);
    			if(father(R,x)!=null)
    				return father(R,x);
    		}
    	}
    	return null;
    }
}

3ms,beats 100%

猜你喜欢

转载自blog.csdn.net/cobracanary/article/details/88944588
今日推荐