问题:
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.
解决:
① 按使用DFS递归遍历,然后判断根节点,左右子树是否相等即可。
/**
* Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { // 0ms public boolean isSameTree(TreeNode p, TreeNode q) { if(p == null && q == null) return true; if(p == null || q == null || p.val != q.val) return false; return isSameTree(p.left,q.left) && isSameTree(p.right,q.right); } }② 非递归方法,使用队列。
public class Solution{ //1ms
public boolean isSameTree(TreeNode p, TreeNode q) { Queue<TreeNode> q1 = new LinkedList<TreeNode>(); Queue<TreeNode> q2 = new LinkedList<TreeNode>(); q1.offer(p); q2.offer(q); while( !q1.isEmpty() && !q2.isEmpty() ) { TreeNode x = q1.poll(); TreeNode y = q2.poll(); if(x==null) { if( y!=null) return false; else continue; } if(y==null || x.val!=y.val) return false; q1.offer( x.left); q1.offer( x.right); q2.offer(y.left); q2.offer(y.right); } return true; } }