提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- [一、力扣1305. 两棵二叉搜索树中的所有元素](#一、力扣1305. 两棵二叉搜索树中的所有元素)
- [二、力扣872. 叶子相似的树](#二、力扣872. 叶子相似的树)
前言
二叉树的构造算法通用思路很简单,无非就是构造根节点,然后递归构造左右子树,最后把它们接起来,关键在于如何找到根节点和左右子树的节点,不同的序列化方法,找根节点的方式也不同
一、力扣1305. 两棵二叉搜索树中的所有元素
java
/**
* 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 {
List<Integer> l1 = new ArrayList<>();
List<Integer> l2 = new ArrayList<>();
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
fun(root1, l1);
fun(root2, l2);
List<Integer> res = new ArrayList<>();
int index1 = 0, index2 = 0;
while(index1 < l1.size() && index2 < l2.size()){
if(l1.get(index1) < l2.get(index2)){
res.add(l1.get(index1));
index1 ++;
}else{
res.add(l2.get(index2));
index2 ++;
}
}
while(index1 < l1.size()){
res.add(l1.get(index1));
index1 ++;
}
while(index2 < l2.size()){
res.add(l2.get(index2));
index2 ++;
}
return res;
}
public void fun(TreeNode root, List<Integer> l){
if(root == null){
return;
}
fun(root.left, l);
l.add(root.val);
fun(root.right, l);
}
}
二、力扣872. 叶子相似的树
java
/**
* 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 {
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
List<Integer> l1 = new ArrayList<>();
List<Integer> l2 = new ArrayList<>();
fun(root1, l1);
fun(root2, l2);
int index = 0;
while(index < l1.size() && index < l2.size()){
if(l1.get(index) != l2.get(index)){
return false;
}
index ++;
}
if(index < l1.size() || index < l2.size()){
return false;
}
return true;
}
public void fun(TreeNode root, List<Integer> l){
if(root == null){
return ;
}
fun(root.left,l);
if(root.left == null && root.right == null){
l.add(root.val);
}
fun(root.right, l);
}
}