872. Leaf-Similar Trees - LeetCode

Question

872. Leaf-Similar Treesjava

Solution

題目大意:code

若是兩個二叉樹的葉子節點相同就認爲這兩個二叉樹類似。給兩個二叉樹判斷是否類似。遞歸

思路:ip

用遞歸把兩個二叉樹的葉子節點遍歷出來,再比較葉子節點是否相同leetcode

Java實現:get

public boolean leafSimilar(TreeNode root1, TreeNode root2) {
    // 把葉子節點遍歷出來,比較
    List<Integer> leftLeafs = new ArrayList<>();
    List<Integer> rightLeafs = new ArrayList<>();
    initLeaf(root1, leftLeafs);
    initLeaf(root2, rightLeafs);
    if (leftLeafs.size() != rightLeafs.size()) return false;
    for (int i = 0; i < leftLeafs.size(); i++) {
        if (leftLeafs.get(i) != rightLeafs.get(i)) return false;
    }
    return true;
}

public void initLeaf(TreeNode root, List<Integer> leafs) {
    if (root.left == null &&  root.right == null) leafs.add(root.val);
    if (root.left != null) initLeaf(root.left, leafs);
    if (root.right != null) initLeaf(root.right, leafs);
}
相關文章
相關標籤/搜索