110. 平衡二叉树
思路: 这题完全是自己的思路解法,没有参照卡哥的。
public bool IsBalanced(TreeNode root) {
if(root == null) return true;
int depth1 = GetDepth(root.left);
int depth2 = GetDepth(root.right);
int diff = depth1 > depth2 ? depth1 - depth2 : depth2 - depth1;
if(diff <= 1)
{
return IsBalanced(root.left) && IsBalanced(root.right);
}
else return false;
}
public int GetDepth(TreeNode node)
{
if(node == null) return 0;
int depth1 = GetDepth(node.left);
int depth2 = GetDepth(node.right);
return depth1 > depth2 ? depth1 + 1 : depth2 + 1;
}
404. 左叶子之和
思路:
- 什么是左叶子结点?首先一定是叶子结点,其次是其父节点的左孩子。
- 做了几道二叉树题目后,我发现二叉树很多题目都是伴随着二叉树前中后序遍历进行的。
public int SumOfLeftLeaves(TreeNode root) {
if(root == null) return 0;
int leftNum = SumOfLeftLeaves(root.left);
if(root.left != null && root.left.left == null && root.left.right == null) leftNum += root.left.val;//二叉树很多题目都是伴随着二叉树前中后序遍历进行的,然后再夹杂着其他逻辑
int rightNum = SumOfLeftLeaves(root.right);
return leftNum + rightNum;
}
257. 二叉树的所有路径
public IList<string> BinaryTreePaths(TreeNode root) {
IList<string> result = new List<string>();
List<int> path = new List<int>();
GetPath(root, result, path);
return result;
}
public void GetPath(TreeNode node, IList<string> result, List<int> path)
{
path.Add(node.val);
if(node.left == null && node.right == null)//当到达叶子结点时,遍历结束。
{
result.Add(string.Join("->",path));
}
if(node.left != null)
{
GetPath(node.left, result, path);//二叉树很多题目都是伴随着二叉树前中后序遍历进行的,然后再夹杂着其他逻辑
path.RemoveAt(path.Count - 1);
}
if(node.right != null)
{
GetPath(node.right, result, path);//二叉树很多题目都是伴随着二叉树前中后序遍历进行的,然后再夹杂着其他逻辑
path.RemoveAt(path.Count - 1);
}
}