//对称二叉树
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public bool IsSymmetric(TreeNode root) {
return IsMirror(root, root);
}
private bool IsMirror(TreeNode r1, TreeNode r2)
{
if(r1 == null && r2 == null)
{
return true;
}
else if(r1 == null || r2 == null || r1.val != r2.val)
{
return false;
}
else
{
return IsMirror(r1.left,r2.right) && IsMirror(r1.right,r2.left);
}
}
}
//543. 二叉树的直径
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public int res;
public int DiameterOfBinaryTree(TreeNode root) {
GetDepth(root);
return res;
}
private int GetDepth(TreeNode root)
{
if(root == null)
return 0;
int leftDepth = GetDepth(root.left);
int rightDepth = GetDepth(root.right);
res = Math.Max(res, leftDepth + rightDepth);
return Math.Max(leftDepth,rightDepth) + 1;
}
}
如果左子树不为空,则最长路径的左端是左子树的最深叶结点,否则最长路径的左端是根结点;
如果右子树不为空,则最长路径的右端是右子树的最深叶结点,否则最长路径的右端是根结点。
因此,子树的最长路径长度为该子树的左子树和右子树的深度之和,子树的深度为该子树的左子树和右子树的深度的较大值加 1。
-
时间复杂度:O(n),其中 n 是二叉树的结点数。每个结点都被访问一次。
-
空间复杂度:O(n),其中 n是二叉树的结点数。空间复杂度主要是递归调用的栈空间,取决于二叉树的高度,最坏情况下是 O(n)。