本文共 875 字,大约阅读时间需要 2 分钟。
给定两颗二叉树,写一个函数判断这两棵树是否相等。如果两棵树的结构和各节点中保存的值是相等的,则认为这两棵树相等。
采用先序遍历的方法,从上到下递归考察各节点。
在任意一对节点的比较中,如果左右枝是否为空的属性和节点中的val值不相等,则认为两棵树不是同一棵树,否则继续考察。如果遍历结束后仍然不能证明这两棵树不是同一棵树,则这两棵树就是相等的实现代码如下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { /** * 判断两个树是否为相等 * @param p 树p * @param q 树q * @return */ public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null && q == null) { return true; } else if ( (p == null && q != null) || (p != null && q == null) || p.val != q.val || !isSameTree(p.left, q.left) || !isSameTree(p.right, q.right)) { return false; } else { return true; } }}
转载地址:http://fxuoi.baihongyu.com/