Same Tree

题目描述:Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.


1 自己的代码

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

public class SameTree {
	public boolean isSameTree(TreeNode p, TreeNode q) {
		boolean isSame = false;
		
		if(p == null && q== null) return true;
		else if((p == null && q != null) || (p != null && q == null)) return false;
		else{//都不为空
			if(p.val == q.val){
				if(isSameTree(p.left, q.left)){
					if(isSameTree(p.right, q.right))
						isSame = true;
				}
			}
		}
        return isSame;
    }
}

你可能感兴趣的:(tree)