文章链接
110.平衡二叉树
平衡二叉树(Balanced Binary Tree) 是指: 任意节点的左右子树高度差不超过 1。
如果当前节点为 null
,返回高度 0
递归获取左子树高度 left
- 如果左子树不平衡(返回 -1),立即返回 -1
递归获取右子树高度 right
- 如果右子树不平衡,立即返回 -1
判断当前节点是否平衡:Math.Abs(left - right) > 1
-
是 → 返回 -1(表示不平衡)
-
否 → 返回当前节点高度:
1 + Math.Max(left, right)
public class Solution {
public bool IsBalanced(TreeNode root) {
return getHeight(root)==-1?false:true;
}
public int getHeight(TreeNode root){
if(root==null) return 0;
int left=getHeight(root.left);
if(left==-1) return -1;
int right=getHeight(root.right);
if(right==-1) return -1;
int res;
if(Math.Abs(right-left)>1){
res=-1;
}else{
res=1+Math.Max(left,right);
}
return res;
}
}
257. 二叉树的所有路径
定义递归函数:使用前序遍历(根 -> 左 -> 右),从根节点出发,记录当前路径。
判断是否为叶子节点:
-
如果当前节点没有左子树和右子树,就是叶子节点。
-
把路径转成字符串加入结果列表中。
回溯处理:每次递归调用结束后,从路径中移除当前节点,避免影响其它路径。
public class Solution {
public IList<string> BinaryTreePaths(TreeNode root) {
List<string> result = new List<string>();
if(root==null) return result;
void DFS(TreeNode node,string path){
if(node==null) return;
path+=node.val;
if(node.left==null&&node.right==null){
result.Add(path);
return;
}
path += "->";
DFS(node.left,path);
DFS(node.right,path);
}
DFS(root,"");
return result;
}
}
404.左叶子之和
左叶子的明确定义:节点A的左孩子不为空,且左孩子的左右孩子都为空(说明是叶子节点),那么A节点的左孩子为左叶子节点
左叶子:是某个节点的左孩子,并且它自己没有左右孩子(即是叶子)。
-
如果当前节点为空,直接返回 0。
-
如果它的 左子节点 是叶子(即左孩子存在,且它没有左右孩子),就把它的值加到总和里。
-
然后递归左右子树,继续找左叶子。
public class Solution {
public int SumOfLeftLeaves(TreeNode root) {
if(root==null) return 0;
int sum=0;
if(root.left!=null&&root.left.left==null&&root.left.right==null){
sum+=root.left.val;
}
sum+=SumOfLeftLeaves(root.left);
sum+=SumOfLeftLeaves(root.right);
return sum;
}
}
222.完全二叉树的节点个数
从根节点开始,分别计算左子树的最左深度 leftDepth
和右子树的最右深度 rightDepth
。
如果 leftDepth == rightDepth
,说明是满二叉树,直接用公式计算节点总数,避免递归。节点个数直接用公式计算:2^(height) - 1
,注意 leftDepth + 1
是整棵树的高度。
如果不相等,说明不是满二叉树,递归分别计算左右子树的节点数量,再加上根节点本身
public class Solution {
public int CountNodes(TreeNode root) {
if(root==null) return =;
var left=root.left;
var right=root.right;
int leftDepth=0,rightDepth=0;
while(left!=null){
left=left.left;
leftDepth++;
}
while(right!=null){
right=right.right;
rightDepth++;
}
if(leftDepth==rightDepth) return (int)Math.Pow(2,leftDepth+1)-1;
return CountNodes(root.left)+CountNodes(root.right)+1;
}
}