本文主要是介绍leetcode100~Same Tree,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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.
该题比较简单,不作解释,不懂的话,欢迎提问~
public class IsSameTree {//递归实现public boolean isSameTree(TreeNode p,TreeNode q) {if(p==null && q==null) return true;if(p==null || q==null) return false;return (p.val==q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);}//非递归public boolean isSameTree2(TreeNode p,TreeNode q) {Stack<TreeNode> stack = new Stack<>();stack.push(p);stack.push(q);while(!stack.isEmpty()) {q=stack.pop();p=stack.pop();if(p==null && q==null) continue;if(p==null || q==null) return false;if(p.val!=q.val) return false;stack.push(p.left);stack.push(q.left);stack.push(p.right);stack.push(q.right);}return true;}
}
这篇关于leetcode100~Same Tree的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!