leetcode 100. Same Tree

来源:互联网 发布:淘宝超时发货赔付规则 编辑:程序博客网 时间:2024/06/03 11:16

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.

这是一道水题。

package leetcode;public class Same_Tree_100 {boolean isEqual=true;public boolean isSameTree(TreeNode p, TreeNode q) {DFS(p, q);return isEqual;}public void DFS(TreeNode p,TreeNode q){if(p==null&&q==null){return;}if((p==null&&q!=null)||p!=null&&q==null){isEqual=false;return;}if(p.val!=q.val){isEqual=false;return;}DFS(p.left,q.left);DFS(p.right,q.right);}public static void main(String[] args) {// TODO Auto-generated method stubSame_Tree_100 s=new Same_Tree_100();TreeNode p=null;TreeNode q=null;System.out.println(s.isSameTree(p, q));}}
有大神跟我思路一样,但是写法更简洁。哎,我的解法就是特别长的那种。。。

public boolean isSameTree(TreeNode p, TreeNode q) {    if(p == null && q == null) return true;    if(p == null || q == null) return false;    if(p.val == q.val)        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);    return false;}
也有不用递归,用栈的写法。
public boolean isSameTree(TreeNode p, TreeNode q) {     Stack<TreeNode> stack_p = new Stack <> ();            Stack<TreeNode> stack_q = new Stack <> ();     if (p != null) stack_p.push( p ) ;     if (q != null) stack_q.push( q ) ;     while (!stack_p.isEmpty() && !stack_q.isEmpty()) {     TreeNode pn = stack_p.pop() ;     TreeNode qn = stack_q.pop() ;         if (pn.val != qn.val) return false ;     if (pn.right != null) stack_p.push(pn.right) ;     if (qn.right != null) stack_q.push(qn.right) ;     if (stack_p.size() != stack_q.size()) return false ;     if (pn.left != null) stack_p.push(pn.left) ;               if (qn.left != null) stack_q.push(qn.left) ;     if (stack_p.size() != stack_q.size()) return false ;     }          return stack_p.size() == stack_q.size() ; }

原创粉丝点击