整理一些关于树的力扣热门算法操作

简介: 整理一些关于树的力扣热门算法操作

8f53862183264aa0bfd2878f46636b27.png

一、LC94、144、145中序,前序,后续遍历


  List<Integer> front = new ArrayList<>();
  List<Integer> mid = new ArrayList<>();
  List<Integer> back = new ArrayList<>();
  //前序遍历
    public void Preorder(TreeNode root){
        if(root == null)
            return;
        front.add(root.val);
        Preorder(root.left);
        Preorder(root.right);
    }
    //中序遍历
    public void Inorder(TreeNode root){
        if(root == null)
            return;
        Inorder(root.left);
        mid.add(root.val);
        Inorder(root.right);
    }
    //后序遍历
    public void Postorder(TreeNode root){
        if(root == null)
            return;
        Postorder(root.left);
        Postorder(root.right);
        back.add(root.val);
    }

二、LC104、111 二叉树最大 最小深度

  // 最大深度
  public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
    }
    // 最小深度
    public int minDepth(TreeNode root) {
        if (root == null){
            return 0;
        }else if (root.left == null || root.right == null){
            return 1;
        }else{
            return Math.min(minDepth(root.left),minDepth(root.right)) + 1;
        }
    }

三、LC100 是否同一棵树

  public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p==null && q==null){
            return true;
        }
        if(p!=null && q!=null && p.val==q.val){
            return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
        }
        return false;
    }

四、LC101 是否对称二叉树

  public boolean isSymmetric(TreeNode root) {
        if(root==null) return true;
        return dfs(root.left,root.right);
    }
    public boolean dfs(TreeNode root1,TreeNode root2){
        if(root1==null&&root2==null) return true;
        if(root1==null || root2==null || root1.val != root2.val) return false;
        return dfs(root1.left,root2.right)&&dfs(root1.right,root2.left);
    }

五、LC110 判断平衡二叉树

  public boolean isBalanced(TreeNode root) {
        if(root==null) return true;
        if(Math.abs(maxDepth(root.left) - maxDepth(root.right)) <=1 ){
            return isBalanced(root.left)&&isBalanced(root.right);
        }
        return false;
    }
    private int maxDepth(TreeNode root){
        if(root==null) return 0;
        return Math.max(getHigh(root.left),getHigh(root.right))+1;
    }

六、LC112 二叉树路径 目标值总和

class Solution {
      public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }
        if (root.left == null && root.right == null) {
            return sum == root.val;
        }
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}


七、LC226 翻转二叉树

  public static TreeNode invertTree(TreeNode root) {
        if (root == null || (root.right == null && root.left == null)){
            return root;
        }
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);
        root.left = right;
        root.right = left;
        return root;
    }

七、判断是否为子树【子树,要么等于,要么等于左/右子树。】

    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null) return false;
        //子树,要么等于,要么等于左/右子树。
        return subFrom(root,subRoot) || isSubtree(root.left,subRoot) || isSubtree(root.right,subRoot);
    }
    public boolean subFrom(TreeNode root, TreeNode subRoot){
        if (root == null && subRoot == null) return true;
        if (root == null || subRoot == null) return false;
        if (root.val != subRoot.val) return false;
        return subFrom(root.left, subRoot.left) && subFrom(root.right, subRoot.right);
    }

八、LC589、590 N叉树的前序 后续遍历

// 前序遍历
class Solution {
    List<Integer> res = new ArrayList<Integer>();
    public List<Integer> preorder(Node root) {
        //递归版
        if(root == null)
            return res;
        res.add(root.val);
        for(Node child : root.children)
        {
            preorder(child);
        }  
        return res;
    }
}
// 后序遍历
class Solution {
    List<Integer> res = new ArrayList<Integer>();
    public List<Integer> postorder(Node root) {
        //递归版
        if(root == null)
            return res;
        for(Node child : root.children)
        {
            postorder(child);
        }
        res.add(root.val);
        return res;
    }
}

九、LC559 N叉树的最大深度

  public int maxDepth(Node root) {
        if(root == null) return 0;
        int max = 0;
        for(Node node : root.children){
            max = Math.max(maxDepth(node),max);
        }
        return max + 1;
    }


十、Offer27 二叉树的镜像

    public TreeNode mirrorTree(TreeNode root) {
        if (root == null)return null;
        TreeNode tmpNode = root.left;
        root.left = mirrorTree(root.right);
        root.right = mirrorTree(tmpNode);
        return root;
    }

十一、NC 是否为二叉搜索树和完全二叉树

  public boolean[] judgeIt (TreeNode root) {
        // write code here
        boolean bst = isBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
        boolean ct = isCompeteTree(root);
        return new boolean[]{bst, ct};
    }
    public boolean isBST(TreeNode root, long lower, long upper) {
        if (null == root) return true;
        if (root.val <= lower || root.val >= upper) {
            return false;
        }
        return isBST(root.left, lower, root.val) && isBST(root.right, root.val, upper);
    }
    public boolean isCompeteTree(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (queue.peek() != null) {
            TreeNode last = queue.poll();
            queue.offer(last.left);
            queue.offer(last.right);
        }
        while (!queue.isEmpty() && queue.peek() == null) {
            queue.poll();
        }
        return queue.isEmpty();
    }

十二、二叉树的最大路径之和


public class MaxPathSumTree {
    int max =Integer.MIN_VALUE;
    public int maxPathSum (TreeNode root) {
        if (root == null) return 0;
        help(root);
        return max;
    }
    public int help(TreeNode root) {
        if(root == null) {
            return 0;
        }
        //如果子节点为负数节点   让他的计算值为0     则一个节点的最大值为 root+left + right
        int left = Math.max(help(root.left), 0);
        int right = Math.max(help(root.right), 0);
        max = Math.max(max, root.val + left + right);
        return  Math.max(root.val + left, root.val + right);
    }
}


十三、LC404 求二叉树左叶子之和

  public static int sumOfLeftLeaves(TreeNode root) {
        int sum = 0;
        if(root == null) return 0;
        if(root.left != null ){
            if(root.left.left == null && root.left.right == null){
                sum += root.left.val;
            }
        }
        sumOfLeftLeaves(root.left);
        sumOfLeftLeaves(root.right);
        return sum;
    }

十四、LC543 二叉树的最大直径【最大路径长度】

class Solution {
    private int max = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        dfs(root);
        return max;
    }
    private int dfs(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = dfs(root.left);
        int rightHeight = dfs(root.right);
        max = Math.max(leftHeight + rightHeight, max);
        return Math.max(leftHeight, rightHeight) + 1;
    }
}

十五、LC102 二叉树层次优先遍历


// 深度优先遍历:
void dfs(TreeNode root) {
    if (root == null) {
        return;
    }
    dfs(root.left);
    dfs(root.right);
}
// 广度优先遍历
void bfs(TreeNode root) {
    Queue<TreeNode> queue = new ArrayDeque<>();
    queue.add(root);
    while (!queue.isEmpty()) {
        TreeNode node = queue.poll(); // Java 的 pop 写作 poll()
        if (node.left != null) {
            queue.add(node.left);
        }
        if (node.right != null) {
            queue.add(node.right);
        }
    }
}


这个题目层次遍历,应该选用BFS

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<List<Integer>>();
        if (root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> level = new ArrayList<Integer>();
            int currentLevelSize = queue.size();
            for (int i = 1; i <= currentLevelSize; ++i) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            ret.add(level);
        }
        return ret;
    }
}


目录
相关文章
|
2月前
|
存储 算法 C语言
"揭秘C语言中的王者之树——红黑树:一场数据结构与算法的华丽舞蹈,让你的程序效率飙升,直击性能巅峰!"
【8月更文挑战第20天】红黑树是自平衡二叉查找树,通过旋转和重着色保持平衡,确保高效执行插入、删除和查找操作,时间复杂度为O(log n)。本文介绍红黑树的基本属性、存储结构及其C语言实现。红黑树遵循五项基本规则以保持平衡状态。在C语言中,节点包含数据、颜色、父节点和子节点指针。文章提供了一个示例代码框架,用于创建节点、插入节点并执行必要的修复操作以维护红黑树的特性。
66 1
|
2月前
|
Python
【Leetcode刷题Python】剑指 Offer 26. 树的子结构
这篇文章提供了解决LeetCode上"剑指Offer 26. 树的子结构"问题的Python代码实现和解析,判断一棵树B是否是另一棵树A的子结构。
38 4
|
7天前
|
大数据 UED 开发者
实战演练:利用Python的Trie树优化搜索算法,性能飙升不是梦!
在数据密集型应用中,高效搜索算法至关重要。Trie树(前缀树/字典树)通过优化字符串处理和搜索效率成为理想选择。本文通过Python实战演示Trie树构建与应用,显著提升搜索性能。Trie树利用公共前缀减少查询时间,支持快速插入、删除和搜索。以下为简单示例代码,展示如何构建及使用Trie树进行搜索与前缀匹配,适用于自动补全、拼写检查等场景,助力提升应用性能与用户体验。
21 2
|
2月前
|
算法
测试工程师的技能升级:LeetCode算法挑战与职业成长
这篇文章通过作者亲身体验LeetCode算法题的过程,探讨了测试工程师学习算法的重要性,并强调了算法技能对于测试职业成长的必要性。
49 1
测试工程师的技能升级:LeetCode算法挑战与职业成长
|
2月前
|
算法 Java
LeetCode经典算法题:矩阵中省份数量经典题目+三角形最大周长java多种解法详解
LeetCode经典算法题:矩阵中省份数量经典题目+三角形最大周长java多种解法详解
39 6
|
2月前
|
存储 算法 Java
LeetCode经典算法题:打家劫舍java详解
LeetCode经典算法题:打家劫舍java详解
53 2
|
2月前
|
人工智能 算法 Java
LeetCode经典算法题:井字游戏+优势洗牌+Dota2参议院java解法
LeetCode经典算法题:井字游戏+优势洗牌+Dota2参议院java解法
41 1
|
2月前
|
存储 算法 Java
LeetCode经典算法题:预测赢家+香槟塔java解法
LeetCode经典算法题:预测赢家+香槟塔java解法
40 1
|
2月前
|
Python
【Leetcode刷题Python】538. 把二叉搜索树转换为累加树
LeetCode上538号问题"把二叉搜索树转换为累加树"的Python实现,使用反向中序遍历并记录节点值之和来更新每个节点的新值。
19 3
|
3月前
|
大数据 UED 开发者
实战演练:利用Python的Trie树优化搜索算法,性能飙升不是梦!
【7月更文挑战第19天】Trie树,又称前缀树,是优化字符串搜索的高效数据结构。通过利用公共前缀,Trie树能快速插入、删除和查找字符串。
83 2
下一篇
无影云桌面