Java教程

Same Tree

本文主要是介绍Same Tree,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Code link: https://leetcode.com/problems/same-tree/

  1. Recursive solution:
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        } else if (p == null || q == null) {
            return false;
        } else if (p.val != q.val) {
            return false;
        }
        
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}
  1. Iterative solution
    We can also use BFS to do level order traversal, with the help of a queue.
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(p);
        queue.add(q);
        
        while (!queue.isEmpty()) {
            TreeNode lNode = queue.remove();
            TreeNode rNode = queue.remove();
            if (lNode == null && rNode == null) {
                continue;
            } else if (lNode == null || rNode == null) {
                return false;
            } else if (lNode.val != rNode.val) {
                return false;
            }
            
            queue.add(lNode.left);
            queue.add(rNode.left);
            queue.add(lNode.right);
            queue.add(rNode.right);

        }
        
        return true;
    }
}

Similar problem:

  • Symmetric tree. The BFS approach is quite similar. The minor difference is the order of adding nodes to the queue.
这篇关于Same Tree的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!