代码随想录算法训练营第十七天|110. 平衡二叉树、404. 左叶子之和、257. 二叉树的所有路径

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);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值