二叉树常见题目

labuladong的算法笔记

遍历

前序遍历
https://leetcode.cn/problems/binary-tree-preorder-traversal/
中序遍历
https://leetcode.cn/problems/binary-tree-inorder-traversal/description/
后序遍历
https://leetcode.cn/problems/binary-tree-postorder-traversal/description/
层序遍历
https://leetcode.cn/problems/binary-tree-level-order-traversal/description/
二叉树的锯齿形层序遍历
https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/description/

二叉树最大深度

https://labuladong.github.io/algo/di-yi-zhan-da78c/shou-ba-sh-66994/dong-ge-da-334dd/

最近公共祖先(Lowest Common Ancestor,简称 LCA)

二叉树的最近公共祖先

https://labuladong.github.io/algo/di-yi-zhan-da78c/shou-ba-sh-66994/git-yuan-l-ba4cf/
https://www.cnblogs.com/labuladong/p/13976582.html
最近公共祖先
说明左子树和右子树均包含 p 节点或 q 节点,如果左子树包含的是 p 节点,那么右子树只能包含 q 节点,反之亦然,因为 p 节点和 q 节点都是不同且唯一的节点,因此如果满足这个判断条件即可说明 x 就是我们要找的最近公共祖先。再来看第二条判断条件,这个判断条件即是考虑了 x 恰好是 p 节点或 q 节点且它的左子树或右子树有一个包含了另一个节点的情况,因此如果满足这个判断条件亦可说明 x 就是我们要找的最近公共祖先。

TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
   
    // 当前节点是null或者p或q中任意一个返回当前节点
    if (root == null) return null;
    if (root == p || root == q) return root;
   	
    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);
    // 情况 1
    if (left != null && right != null) {
   
        return root;
    }
    // 情况 2
    if (left == null && right == null) {
   
        return null;
    }
    // 情况 3
    return left == null ? right : left;
}

二叉树中和为目标值的路径

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
解题过程参考
https://leetcode.cn/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/solutions/154060/mian-shi-ti-34-er-cha-shu-zhong-he-wei-mou-yi-zh-5/
这篇文章使用的回溯算法实现的

class Solution {
   
    LinkedList<List<Integer>> res 
  • 24
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值