【问题标题】:Understanding recursion function while checking if a binary tree is a subtree of another one在检查二叉树是否是另一棵二叉树的子树时理解递归函数
【发布时间】:2021-03-30 15:38:02
【问题描述】:

我试图了解树 t 是否是树 s 的子树。我有以下代码,但它不起作用。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

class Solution {
    private boolean result = false;
    public boolean isSubtree(TreeNode s, TreeNode t) {
        return isTinS(s, t);
    }
    
    public boolean isTinS(TreeNode s, TreeNode t) {
        if (t==null) return true;
        if (s==null) return false;

        if (s.val == t.val) {
           return isSame(s,t);
        }
        return isTinS(s.left, t) || isTinS(s.right, t);
    }
    
    public boolean isSame(TreeNode s, TreeNode t) {
        if (s==null && t==null) return true;
        if (s==null || t==null) return false;
        return s.val==t.val && isSame(s.left, t.left) && isSame(s.right, t.right);
    }
}

如果我更改 isTinS 函数中的 if 条件,它会起作用。我很难弄清楚这两个代码之间的区别。

    public boolean isTinS(TreeNode s, TreeNode t) {
        if (t==null) return true;
        if (s==null) return false;
     
        if (isSame(s,t)) {
            return true;
        }
        return isTinS(s.left, t) || isTinS(s.right, t);
    }

有人能解释一下它们有何不同,或者给我指出一些很好的资源来理解这些概念吗?

【问题讨论】:

    标签: java recursion binary-tree


    【解决方案1】:

    假设t 根处的值在s 中出现两次,但其中只有一个出现在与t 匹配的子树的根处。如果您的第一个代码首先打错了,它将返回 false 并且永远不会继续寻找另一个,而第二个代码将继续搜索。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-20
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-24
      相关资源
      最近更新 更多