Open songyy5517 opened 5 months ago
Approach: DFS
Complexity Analysis
/**
* 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 {
ArrayList<Integer> a1 = new ArrayList();
ArrayList<Integer> a2 = new ArrayList();
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
// Intuitioin: Collect all leaf nodes through DFS, and then compare.
// 1. Exception handling
if (root1 == null || root2 == null)
return false;
dfs(root1, a1);
dfs(root2, a2);
return a1.equals(a2);
}
void dfs(TreeNode root, ArrayList<Integer> a){
if (root == null)
return ;
if (root.left == null && root.right == null)
a.add(root.val);
dfs(root.left, a);
dfs(root.right, a);
}
}
2024/5/30
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence. 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.
Example 1:
Example 2:
Intuition The problem is to compare whether the value and sequence of the leaf nodes of two binary trees are the same. A simple idea is to travarse two trees with DFS, and extract all their leaf nodes into a container, and finally compare whether the elements in two containers are equal.