Pseudocode to compare two trees

后端 未结 5 1984
猫巷女王i
猫巷女王i 2021-02-02 11:11

This is a problem I\'ve encountered a few times, and haven\'t been convinced that I\'ve used the most efficient logic.

As an example, presume I have two trees: one is a

5条回答
  •  悲哀的现实
    2021-02-02 11:58

    public boolean compareTrees(TreeNode root1, TreeNode root2) {
      if ((root1 == null && root2 != null) || 
          (root1 != null && root2 == null)) {
        return false;
      }
    
      if (root1 == null && root2 == null) {
        return true;
      }
    
      if (root1.data != root2.data) {
        return false;
      }
    
      return compareTrees(root1.left, root2.left) && 
        compareTrees(root1.right, root2.right);
    }
    

提交回复
热议问题