Leatcode 872-Leaf Similar Tree(叶子相似的树)

Leatcode 872-Leaf Similar Tree(叶子相似的树)

题目描述

Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.

For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).

Two binary trees are considered leaf-similar if their leaf value sequence is the same.

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

Note:

Both of the given trees will have between 1 and 100 nodes.

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

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

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

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

提示:

给定的两颗树可能会有 1 到 100 个结点。

解法一:递归 + ArrayList

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
	 // 解法一:递归 + ArrayList
     public boolean leafSimilar(TreeNode root1, TreeNode root2) {
        List<Integer> sequence1 = new ArrayList<Integer>();
        List<Integer> sequence2 = new ArrayList<Integer>();
        this.leafSequence(root1, sequence1);
        this.leafSequence(root2, sequence2);
        if(sequence1.size() != sequence2.size()){
            return false;
        }
        for(int i = 0; i < sequence1.size(); i ++){
            if(sequence1.get(i) != sequence2.get(i)){
                return false;
            }
        }
        return true;
    }
    private void leafSequence(TreeNode root, List<Integer> res){
        if(root == null){
            return;
        }
        if(root.left == null && root.right == null){
            res.add(root.val);
        }
        leafSequence(root.left, res);
        leafSequence(root.right, res);
    }
}

解法二:递归 + StringBuilder

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
	public boolean leafSimilar(TreeNode root1, TreeNode root2) {
        String sequence1 = getLeafValues(root1, new StringBuilder()).toString();
        String sequence2 = getLeafValues(root2, new StringBuilder()).toString();
        if(sequence1.equals(sequence2)){
            return true;
        }
        return false;
        // 三目运算符一行可代替以上代码
        //return getLeafValues(root1, new StringBuilder()).toString().equals(getLeafValues(root2, new StringBuilder()).toString())  ? true : false;
    }
    private StringBuilder getLeafValues(TreeNode root, StringBuilder sb) {
        if(root == null) {
            return sb;
        }
        if(root.left == null && root.right == null) {
            sb.append("" + root.val);
            return sb;
        }
        getLeafValues(root.left, sb);
        getLeafValues(root.right, sb);
        return sb;
    }
}

猜你喜欢

转载自blog.csdn.net/PerryJennings/article/details/83243829
今日推荐