题解 | #相逆叶子#
相逆叶子
https://www.nowcoder.com/practice/41c7b0e8710e43ca9f328bf06ea2aff3
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*借助栈进行二叉树的遍历,题目中只比对叶子节点,创建两个 list1,list2,list1存储从左到右 root1 的叶子节点,list2 存储 root2 从右到左叶子节点。先比对 list1 和 list2 大小是否一致,再遍历比对即可。
*
* @param root1 TreeNode类
* @param root2 TreeNode类
* @return bool布尔型
*/
public boolean leafSimilar (TreeNode root1, TreeNode root2) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> list1 = new ArrayList<>();
stack.push(root1);
while (!stack.isEmpty()) {
TreeNode temp = stack.pop();
if (temp.left == null && temp.right == null) {
list1.add(temp.val);
}
if (temp.left != null) {
stack.push(temp.left);
}
if (temp.right != null) {
stack.push(temp.right);
}
}
List<Integer> list2 = new ArrayList<>();
stack.push(root2);
while (!stack.isEmpty()) {
TreeNode temp = stack.pop();
if (temp.left == null && temp.right == null) {
list2.add(temp.val);
}
if (temp.right != null) {
stack.push(temp.right);
}
if (temp.left != null) {
stack.push(temp.left);
}
}
if(list1.size() != list2.size()){
return false;
}
for(int i = 0;i<list1.size();i++){
if(list1.get(i) != list2.get(i)){
return false;
}
}
return true;
}
}
查看10道真题和解析