1. 程式人生 > >leetcode解題之100# Same Tree Java版

leetcode解題之100# Same Tree Java版

100. 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.

給定兩個二叉樹,判斷這兩棵樹是否相等。
僅當兩棵樹的結構相同,結點值都相等時都會相等。

使用遞迴進行求解,先判斷當前結點值是否相等,如果相等就再比較其左右子樹,只有當所有的結點都相等才相等。

   //樹節點
	public class TreeNode {
		    int val;
		      TreeNode left;
		      TreeNode right;
		      TreeNode(int x) { val = x; }
		  }

 public boolean isSameTree(TreeNode p, TreeNode q) {
		 if(p==null&&q==null)
			 return true;
		 if(p!=null&&q==null)
			 return false;
		 if(p==null&&q!=null)
			 return false;
		 return q.val==p.val&&isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
	 }