LeetCode [简单] 对称二叉树&二叉树的直径

101. 对称二叉树 - 力扣(LeetCode)

//对称二叉树
/**
 * 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. 二叉树的直径 - 力扣(LeetCode)

//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)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值