第一次遇见Tree的题,拿到心慌,网上查了解题思路。写完就三行。。
最近努力学习一句话,学会喜欢自己。
题目:give two tree , you must judge if they are the same tree. ensure they are the same tree structure and node value.
开始思路:我想保存下tree的中序遍历,来判断tree是否相等,但是这块代码不会写。
解题思路:递归遍历两颗树,比较节点值是否相等。如果相等,则递归比较两颗树的leftSubTree 和 rightSubTree。注意:当出现任意一棵为Null 而另一棵不为Null 时,无条件返回false.
code:(Java)
public boolean isSameTree(TreeNode p, TreeNode q) { if(p == null && q == null) return true; // both trees are null if(p == null && q != null || p != null && q == null || p.val != q.val) return false; // Any tree is null or their node value is different return isSameTree(p.left , q.left) && isSameTree(p.right , q.right); // recursive compare their leftSubTree and rightSubTree }