Skip to content

Latest commit

 

History

History
175 lines (132 loc) · 4.57 KB

File metadata and controls

175 lines (132 loc) · 4.57 KB

English Version

题目描述

请考虑一棵二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个 叶值序列

举个例子,如上图所示,给定一棵叶值序列为 (6, 7, 4, 9, 8) 的树。

如果有两棵二叉树的叶值序列是相同,那么我们就认为它们是 叶相似 的。

如果给定的两个头结点分别为 root1 和 root2 的树是叶相似的,则返回 true;否则返回 false

 

示例 1:

输入:root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]
输出:true

示例 2:

输入:root1 = [1], root2 = [1]
输出:true

示例 3:

输入:root1 = [1], root2 = [2]
输出:false

示例 4:

输入:root1 = [1,2], root2 = [2,2]
输出:true

示例 5:

输入:root1 = [1,2,3], root2 = [1,3,2]
输出:false

 

提示:

  • 给定的两棵树可能会有 1 到 200 个结点。
  • 给定的两棵树上的值介于 0200 之间。

解法

深度优先搜索。

Python3

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
        def dfs(root, leaves):
            if root is None:
                return
            if root.left is None and root.right is None:
                leaves.append(root.val)
                return
            dfs(root.left, leaves)
            dfs(root.right, leaves)
        l1, l2 = [], []
        dfs(root1, l1)
        dfs(root2, l2)
        return l1 == l2

Java

/**
 * 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 {
    public boolean leafSimilar(TreeNode root1, TreeNode root2) {
        List<Integer> l1 = new ArrayList<>();
        List<Integer> l2 = new ArrayList<>();
        dfs(root1, l1);
        dfs(root2, l2);
        return l1.equals(l2);
    }

    private void dfs(TreeNode root, List<Integer> leaves) {
        if (root == null) return;
        if (root.left == null && root.right == null) {
            leaves.add(root.val);
            return;
        }
        dfs(root.left, leaves);
        dfs(root.right, leaves);
    }
}

Go

func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool {
	var l1, l2 []int
	if root1 != nil {
		dfs(root1, &l1)
	}
	if root2 != nil {
		dfs(root2, &l2)
	}
	return reflect.DeepEqual(l1, l2)
}

func dfs(root *TreeNode, leaves *[]int) {
	if root.Left == nil && root.Right == nil {
		*leaves = append(*leaves, root.Val)
	} else {
		if root.Left != nil {
			dfs(root.Left, leaves)
		}
		if root.Right != nil {
			dfs(root.Right, leaves)
		}
	}
}

...