LeetCode - 872. Leaf-Similar Trees

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

LeetCode - 872. Leaf-Similar Trees

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); }
}
上一篇:opencv 连通域需要的函数解析


下一篇:从Nexus私服下载和上传资源(二)