100. Same Tree(leetcode)

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.

题意大概是:给定两个二叉树,编写一个函数检查它们是否相等。如果结构相同且节点具有相同的值,则两个二叉树被认为是相等的。

题目给出了树的节点类

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

我们最容易想到的,是用栈来实现:

 1 import java.util.*;
 2 public class Solution {
 3     static Stack<TreeNode> stack1=new Stack<TreeNode>();
 4     static Stack<TreeNode> stack2=new Stack<TreeNode>();
 5     public void toStack(TreeNode p,TreeNode q)
 6     {
 7         while(p.left!=null)
 8         {stack1.push(p);
 9          p=p.left;   }
10          while(q.left!=null)
11         {stack2.push(q);
12          q=q.left;    }
13         stack1.push(p);
14         stack2.push(q);
15 
16   
17     }
18     public boolean isSameTree(TreeNode p, TreeNode q) { 
19         if((p==null&&q==null))
20             return true;
21         if(p==null||q==null)
22             return false;
23         while(!stack1.isEmpty())
24             stack1.pop();
25         while(!stack2.isEmpty())
26             stack2.pop();
27         TreeNode a,b;
28         toStack(p,q);
29             while(!stack1.isEmpty()&&!stack2.isEmpty())
30             {
31                 a=stack1.pop();   
32                 b=stack2.pop();
33                   if(a.val!=b.val)//判断该节点的值是否相等
34                      return false;  
35   
36                     if((a.right!=null)&&(b.right!=null))//都有右孩子,让他们入栈
37                             toStack(a.right,b.right);
38 
39                     else if((a.right==null&&b.right!=null)||a.right!=null&&b.right==null)//有一个有右孩子,另外一个没有右孩子
40                         return false; 
41             }
42         
43         if(stack1.isEmpty()&&stack2.isEmpty())
44               return true;         
45         return false;
46     }
47     
48 }

当然,还有更简单的,用递归搞定:

1 public boolean isSameTree(TreeNode p, TreeNode q) {
2     if(p == null && q == null) return true;
3     if(p == null || q == null) return false;
4     if(p.val == q.val)
5         return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
6     return false;
7 }

更新:

上面两行

     if(p == null && q == null) return true;
     if(p == null || q == null) return false;

可以用一行代替:

if (p == NULL || q == NULL) return (p == q);
原文地址:https://www.cnblogs.com/jachin01/p/7275007.html