前序遍历,记录叶子节点即可
class Solution {
private static String ans = "";
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
ans = "";
String ans1 = "", ans2 = "";
fun(root1);
ans1 = ans;
ans = "";
fun(root2);
ans2 = ans;
return ans1.equals(ans2);
}
public void fun(TreeNode treeNode) {
if (treeNode.left == null && treeNode.right == null) {
ans += treeNode.val;
}
if (treeNode.left != null) {
fun(treeNode.left);
}
if (treeNode.right != null) {
fun(treeNode.right);
}
}
}