暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

二叉树-天然的递归

码农历险技 2019-11-04
594

二叉树在结构上的设计就是一种递归结构,

根节点A有左子树{B,C,D}和右子树{E,F};

根节点A的左子树{B,C,D}的根节点B;

根节点A的左子树{B,C,D}的根节点B的左子树C;

根节点A的左子树{B,C,D}的根节点B的右子树D;

......

这样一直递归过去就构成了一颗完整的二叉树。

根据递归的性质就可以解决很多二叉树的题目啦,下面来几道题体会一下二叉树的递归。

一.二叉树的最大深度

直接用递归,求出根节点root的深度,再调用递归函数求出左子树和右子树的深度,最后root的深度加上左右子树的深度取最大的那一个就行了。

public class ErChaShu {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public int maxDepth(TreeNode root) {
if(root==null) return 0;
if(root.left==null && root.right==null) return 1;
int left_height=maxDepth(root.left);
int right_height=maxDepth(root.right);
int result=Math.max(left_height,right_height);
return result+1; //还要加上root的高度1
}
}

LeeCode上运行结果:


二.路径总和

同样的,当根节点的左右子树都为空的时候直接判断跟节点符不符合条件,当跟节点的左右子树不为空直接调用左右子树的递归函数就可以了。

public class ErChaShu {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}

public boolean hasPathSum(TreeNode root,

int sum) {

if(root==null) return false;
int result=sum-root.val;
if(root.left==null && root.right==null){
return result==0;
}else{
return hasPathSum(root.left,result)
|| hasPathSum(root.right,result);
}
}
}

LeeCode上运行结果:


二叉树很多题型我们只要找出递归条件的终止条件,再用递归函数一直递归下去直到终止条件为止,很多难题都迎刃而解了。


文章转载自码农历险技,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论