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

Solution:

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public boolean isSameTree(TreeNode r1, TreeNode r2) {
12         // Start typing your Java solution below
13         // DO NOT write main() function
14         if(r1 == null && r2 == null) 
15             return true;
16         if(r1 == null || r2 == null)
17             return false;
18         if(r1.val != r2.val)
19             return false;
20         return isSameTree(r1.left, r2.left) && isSameTree(r1.right, r2.right);
21     }
22 }

 

posted @ 2013-01-28 08:43  cradle  阅读(221)  评论(0编辑  收藏  举报