题目描述
请考虑一颗二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个 叶值序列 。
872. 叶子相似的树
解法1 迭代
前序遍历得到二叉树的叶值序列,然后将它们比较即可。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
if (root1 == null || root2 == null) {
return false;
}
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
list1 = helper(root1);
list2 = helper(root2);
if (list1.equals(list2)) {
return true;
}
return false;
}
public List<Integer> helper(TreeNode root) {
List<Integer> list = new ArrayList<>();
LinkedList<TreeNode> stack = new LinkedList<>();
while (!stack.isEmpty() || root != null) {
while (root != null) {
if (root.left == null && root.right == null) {
list.add(root.val);
}
stack.push(root);
root = root.left;
}
root = stack.pop();
root = root.right;
}
return list;
}
}
解法2 递归
上面的思路,用递归实现了一遍
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
if (root1 == null || root2 == null) {
return false;
}
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
helper(root1, list1);
helper(root2, list2);
if (list1.equals(list2)) {
return true;
}
return false;
}
public void helper(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
list.add(root.val);
}
helper(root.left, list);
helper(root.right, list);
}
}