题解 | #相逆叶子#
相逆叶子
https://www.nowcoder.com/practice/41c7b0e8710e43ca9f328bf06ea2aff3
知识点:层序遍历
思路:拿到叶子节点就行了,层序遍历是其中的一种方式,当然你可以用其他的方式,我这里用两个栈来存储叶子节点
编程语言:java
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 { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root1 TreeNode类 * @param root2 TreeNode类 * @return bool布尔型 */ public boolean leafSimilar(TreeNode root1, TreeNode root2) { Stack<Integer> stack1 = new Stack<>(); Stack<Integer> stack2 = new Stack<>(); pushLeftLeaves(root1, stack1); pushRightLeaves(root2, stack2); return stack1.equals(stack2); } private void pushLeftLeaves(TreeNode node, Stack<Integer> stack) { if (node != null) { if (node.left == null && node.right == null) { stack.push(node.val); } else { pushLeftLeaves(node.left, stack); pushLeftLeaves(node.right, stack); } } } private void pushRightLeaves(TreeNode node, Stack<Integer> stack) { if (node != null) { if (node.left == null && node.right == null) { stack.push(node.val); } else { pushRightLeaves(node.right, stack); pushRightLeaves(node.left, stack); } } } }