zoukankan      html  css  js  c++  java
  • 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);
            
        }
    }
  • 相关阅读:
    Java内存分析工具MAT
    jvisualvm安装Visual GC插件
    Jmeter取样器之JDBC Request
    tomcat监控页面
    高并发的参数优化(Tomcat、数据库、linux服务器)
    UITableView自定义Section
    iPhone的动画效果类型及实现方法
    自定义UITableViewCell详细步骤
    扩展NSDate类(NSDateHelper)
    UITableView实现Cell的滑动删除
  • 原文地址:https://www.cnblogs.com/wxisme/p/9370244.html
Copyright © 2011-2022 走看看