LeetCode 872.叶子相似的树

题目

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

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

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

思路:在深度优先搜索的过程中,我们总是先搜索当前节点的左子节点,再搜索当前节点的右子节点。如果我们搜索到一个叶节点,就将它的值放入序列中。

代码

/**
 * 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> seq1 = new ArrayList<>();
        if (root1 != null)
            dfs(seq1, root1);
        List<Integer> seq2 = new ArrayList<>();
        if (root2 != null)
            dfs(seq2, root2);
        return seq1.equals(seq2);
    }
    private void dfs(List<Integer> seq, TreeNode root) {
        if (root.left == null && root.right == null) {
            seq.add(root.val);
        } else {
            if (root.left != null)
                dfs(seq, root.left);
            if (root.right != null)
                dfs(seq, root.right);
        }
    }
}

性能

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值