• LeetCode


    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.

    先序遍历,找到叶子节点依次比较

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        private List<TreeNode> nodes1 = new ArrayList<>();
        private List<TreeNode> nodes2 = new ArrayList<>();
        public boolean leafSimilar(TreeNode root1, TreeNode root2) {
            frontTraversal(root1, nodes1);
            frontTraversal(root2, nodes2);
            int len1 = nodes1.size();
            int len2 = nodes2.size();
            if (len1 != len2)
                return false;
            for (int i=0; i<len1; i++) {
                if (nodes1.get(i).val != nodes2.get(i).val)
                    return false;
            }
            return true;
        }
        
        public void frontTraversal(TreeNode root, List<TreeNode> nodes) {
            if (root == null)
                return;
            if (root.left != null)
                frontTraversal(root.left, nodes);
            if (root.left == null && root.right == null)
                nodes.add(root);
            if (root.right != null)
                frontTraversal(root.right, nodes);
            
        }
    }
  • 相关阅读:
    curl查询公网出口IP
    Linux scp命令
    docker 安装 MySQL 8.0
    Ubuntu下apt方式安装与更新Git
    第2章 一切都是对象
    Mave实战(1)——Maven介绍
    关于Identityserver4和IdentityServer3 授权不兼容的问题
    装箱和拆箱、类型比较
    接口自动化用例(Fitnesse)中批量获取系统链路日志
    man时括号里的数字是啥意思
  • 原文地址:https://www.cnblogs.com/wxisme/p/9370244.html
Copyright © 2020-2023  润新知