提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
有些题目,你按照拍脑袋的方式去做,可能发现需要在递归代码中调用其他递归函数计算字数的信息。一般来说,出现这种情况时你可以考虑用后序遍历的思维方式来优化算法,利用后序遍历传递子树的信息,避免过高的时间复杂度
一、力扣1379. 找出克隆二叉树中的相同节点
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode res = null;
public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {
fun(original,cloned,target);
return res;
}
public void fun(TreeNode original, TreeNode cloned, TreeNode target){
if(original == null){
return;
}
if(original == target){
res = cloned;
return;
}
fun(original.left,cloned.left,target);
fun(original.right,cloned.right,target);
}
}
二、力扣LCR 143. 子结构判断
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSubStructure(TreeNode A, TreeNode B) {
if(B == null){
return false;
}
if(A == null){
return B == null;
}
if(fun(A,B)){
return true;
}
return isSubStructure(A.left,B) || isSubStructure(A.right,B);
}
public boolean fun(TreeNode A , TreeNode B){
if (B == null) {
return true;
}
if (B != null && A == null) {
return false;
}
if(A.val != B.val){
return false;
}
return fun(A.left,B.left) && fun(A.right,B.right);
}
}
三、力扣110. 平衡二叉树
/**
* 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 {
boolean flag = true;
public boolean isBalanced(TreeNode root) {
fun(root);
return flag;
}
public int fun(TreeNode root){
if(root == null){
return 0;
}
int l = fun(root.left);
int r = fun(root.right);
if(Math.abs(l-r) > 1){
flag = false;
}
return l > r ? l + 1:r +1;
}
}
四、力扣250. 统计同值子树
/**
* 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 int countUnivalSubtrees(TreeNode root) {
if(root == null){
return 0;
}
int cur = 0;
if(fun(root,root.val)){
cur = 1;
}
int l = countUnivalSubtrees(root.left);
int r = countUnivalSubtrees(root.right);
return cur + l + r;
}
public boolean fun(TreeNode root,int val){
if(root == null){
return true;
}
if(root.val != val){
return false;
}
return fun(root.left,val) && fun(root.right,val);
}
}
本文介绍了如何通过后序遍历优化递归算法,解决LeetCode中的四个二叉树相关问题:1379找出克隆二叉树中的相同节点、143子结构判断、110平衡二叉树及250统计同值子树,展示了如何在递归中传递子树信息以降低时间复杂度。
742

被折叠的 条评论
为什么被折叠?



