[US Giants] 七. Binary Tree

本文详细介绍了二叉树的各种操作,包括平衡二叉树的判定、插入节点到二叉搜索树、利用前序与中序遍历构建二叉树、通过中序与后序遍历构建二叉树以及在二叉搜索树中移除节点等核心算法。
Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example

Given binary tree A = {3,9,20,#,#,15,7}, B = {3,#,20,15,7}

A)  3            B)    3 
   / \                  \
  9  20                 20
    /  \                / \
   15   7              15  7

The binary tree A is a height-balanced binary tree, but B is not.

思路:如果左右subtree有一个不平衡,就不符合要求

         如果左右subtree都是平衡的,但是要符合两边高度差不能大于1

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: True if this Binary tree is Balanced, or false.
     */
    
    public boolean isBalanced(TreeNode root) {
        return helper(root)!=-1;
    }
    
    private int helper(TreeNode root){
        if(root==null){
            return 0;
        }
     
        int leftDepth=helper(root.left);
        int rightDepth=helper(root.right);
        if(leftDepth==-1 || rightDepth==-1 || Math.abs(leftDepth-rightDepth)>1){
            return -1;
        }
        return Math.max(leftDepth,rightDepth)+1;
    }
}
Insert Node in a Binary Search Tree

Given a binary search tree and a new tree node, insert the node into the tree. You should keep the tree still be a valid binary search tree.

You can assume there is no duplicate values in this tree + node.

Example

Given binary search tree as follow, after Insert node 6, the tree should be:

  2             2
 / \           / \
1   4   -->   1   4
   /             / \ 
  3             3   6
Challenge Can you do it without recursion?
思路:由于是BST,而且题目给出条件tree+node里没有重复值,因此node的去向就是两种,要么root左边,要么root右边

         如果node的值比当前root值小,去向就是左边,继续找,如果左边值不为null,继续判断,如果为null,就直接赋值node为这个位置

         如果node的值比当前root值大,去向就是右边,继续找,如果右边值不为null,继续判断,如果为null,就直接赋值node为这个位置       

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {                                         //non-recursion
    /**
     * @param root: The root of the binary search tree.
     * @param node: insert this node into the binary search tree
     * @return: The root of the new binary search tree.
     */
    public TreeNode insertNode(TreeNode root, TreeNode node) {
        if(root==null){
            return node;
        }
        
        TreeNode cur=root;
        while(true){                                           //因为while(true)是一个无限循环,表达式一直为真
            if(node.val<cur.val){                              //需要break跳出循环
                if(cur.left!=null){
                   cur=cur.left; 
                }else{
                   cur.left=node;
                   break;
                }
            }else if(node.val>cur.val){
                if(cur.right!=null){
                   cur=cur.right; 
                }else{
                   cur.right=node;
                   break;
                }
            }
        }
        return root;
    }
}

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {                                         //recursion
    /**
     * @param root: The root of the binary search tree.
     * @param node: insert this node into the binary search tree
     * @return: The root of the new binary search tree.
     */
    public TreeNode insertNode(TreeNode root, TreeNode node) {
        if(root==null){
            return node;                                        //这里写成root=node是一样的
        }
        if(node.val<root.val){
            root.left=insertNode(root.left, node);
        }else{                                                  //因为题目指出没有duplicates,因此else的情况就是
            root.right=insertNode(root.right, node);            //node.val>root.val
        }
        return root;
    }
}
Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

You may assume that duplicates do not exist in the tree.

Example

Given in-order [1,2,3] and pre-order [2,1,3], return a tree:

  2
 / \
1   3
思路:preorder的第一个元素就是要建立的二叉树的root,在inorder数组里找到root的位置,也就是值等于prorder[pstart]的位置,记为pos

         pos的前面的就是左子树,pos的后面的就是右子树

注意:左右子树递归的时候,找preorder开始和结束位置的边界的时候,长度可以由inorder的长度来计算

         例如root.left=build(inoder,istart,pos-1,preorder,pstart+1,end);

         end值的计算:根据inorder部分计算左子树占据的数组长度,pos-1-istart+1=pos-istart

         因此preorder这部分的长度也是pos-istart,又因为preorder从pstart开始,所以最后知end为pstart+pos-istart

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
 
 
public class Solution {
    /**
     *@param preorder : A list of integers that preorder traversal of a tree
     *@param inorder : A list of integers that inorder traversal of a tree
     *@return : Root of a tree
     */
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder==null || inorder==null){
            return null;
        }
        if(preorder.length!=inorder.length){
            return null;
        }
        return build(inorder,0,inorder.length-1,preorder,0,preorder.length-1);      
    }
    
    private TreeNode build(int[] inorder,int istart,int iend,int[] preorder,int pstart,int pend){
        if(istart>iend){                                                         //这边写成pstart<pend也是一样的
            return null;
        }
        int pos=findPosition(inorder,istart,iend,preorder[pstart]);
        TreeNode root=new TreeNode(preorder[pstart]);
        root.left=build(inorder,istart,pos-1,preorder,pstart+1,pstart+pos-istart); 
        root.right=build(inorder,pos+1,iend,preorder,pstart+pos-istart+1,pend);  //preorder的右边开始位置是
        return root;                                                             //preorder左边结束位置+1
    } 
     
    private int findPosition(int[] arr,int start,int end,int pos){
        for(int i=start;i<=end;i++){
            if(arr[i]==pos){
                return i;
            }
        }
        return -1;
    }
}
Construct  Binary Tree from inorder and postorder traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

You may assume that duplicates do not exist in the tree.

Example

Given inorder [1,2,3] and postorder [1,3,2], return a tree:

  2
 / \
1   3

思路:和inorder,preorder建树的思路一样

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder.length!=postorder.length){
            return null;
        }
        return build(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
    }
    
    public TreeNode build(int[] inorder,int istart,int iend, int[] postorder,int pstart,int pend) {
        if(istart>iend){
            return null;
        }
        TreeNode root=new TreeNode(postorder[pend]);
        int pos=finPos(inorder,istart,iend,postorder[pend]);
        root.left=build(inorder,istart,pos-1,postorder,pstart,pstart+pos-istart-1);
        root.right=build(inorder,pos+1,iend,postorder,pstart+pos-istart,pend-1);
        return root;
    }
    
    private int finPos(int[] arr,int start,int end,int pos){
        for(int i=start;i<=end;i++){
            if(arr[i]==pos){
                return i;
            }
        }
        return -1;
    }
}
Remove Node in Binary Search Tree

Given a root of Binary Search Tree with unique value for each node. Remove the node with given value. If there is no such a node with given value in the binary search tree, do nothing. You should keep the tree still a binary search tree after removal.

Example

Given binary search tree:

    5
   / \
  3   6
 / \
2   4            当前root下有两个结点,找右面最小值,此时为4,把4赋值到当前root,再对4进行递归,此时value=4,下面没有结点,返回null

Remove 3, you can either return:

    5
   / \
  2   6
   \
    4

or

    5
   / \
  4   6
 /
2                本题解法就是最后建立这样一颗树
思路:考虑到三种情况:

         要删除的node下面没有结点,直接把此结点设为null

         要删除的node下面只有一个或左或右的结点,或者是说只有左子树或者只有右子树,直接返回这颗树

         要删除的node下面有两个结点,找到右子树的最小值结点,根据BST知,最小值结点一定在左面,或者就是它自己,

         把找到的最小值赋值到当前node的值,

         对于当前node的右子树再进行同样的递归,此时要递归删除的value就是刚才找到的右子树的最小值点

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of the binary search tree.
     * @param value: Remove the node with given value.
     * @return: The root of the binary search tree after removal.
     */
    public TreeNode removeNode(TreeNode root, int value) {
        if(root==null){
            return null;
        }
        
        if(value>root.val){
            root.right=removeNode(root.right, value);
        }else if(value<root.val){
            root.left=removeNode(root.left, value);
        }else{
            if(root.left==null && root.right==null){
                return null;
            }
            if(root.left==null){
                return root.right;
            }
            if(root.right==null){
                return root.left;
            }
            TreeNode minRight=findNode(root.right);
            root.val=minRight.val;
            root.right=removeNode(root.right,minRight.val);       //此时要递归的value就是刚才找到的右子树最小值
        }
        return root;
    }
    
    private TreeNode findNode(TreeNode cur){
        while(cur.left!=null){
            cur=cur.left;
        }
        return cur;
    }
}






【SCI一区复现】基于配电网韧性提升的应急移动电源预配置和动态调度(下)—MPS动态调度(Matlab代码实现)内容概要:本文档围绕“基于配电网韧性提升的应急移动电源预配置和动态调度”主题,重点介绍MPS(Mobile Power Sources)动态调度的Matlab代码实现,是SCI一区论文复现的技术资料。内容涵盖在灾害或故障等极端场景下,如何通过优化算法对应急移动电源进行科学调度,以提升配电网在突发事件中的恢复能力与供电可靠性。文档强调采用先进的智能优化算法进行建模求解,并结合IEEE标准测试系统(如IEEE33节点)进行仿真验证,具有较强的学术前沿性和工程应用价值。; 适合人群:具备电力系统基础知识和Matlab编程能力,从事电力系统优化、配电网韧性、应急电源调度等相关领域研究的研究生、科研人员及工程技术人员。; 使用场景及目标:①用于复现高水平期刊(SCI一区、IEEE顶刊)中关于配电网韧性与移动电源调度的研究成果;②支撑科研项目中的模型构建与算法开发,提升配电网在故障后的快速恢复能力;③为电力系统应急调度策略提供仿真工具与技术参考。; 阅读建议:建议结合前篇“MPS预配置”内容系统学习,重点关注动态调度模型的数学建模、目标函数设计与Matlab代码实现细节,建议配合YALMIP等优化工具包进行仿真实验,并参考文中提供的网盘资源获取完整代码与数据。
一款AI短视频生成工具,只需输入一句产品卖点或内容主题,软件便能自动生成脚本、配音、字幕和特效,并在30秒内渲染出成片。 支持批量自动剪辑,能够实现无人值守的循环生产。 一键生成产品营销与泛内容短视频,AI批量自动剪辑,高颜值跨平台桌面端工具。 AI视频生成工具是一个桌面端应用,旨在通过AI技术简化短视频的制作流程。用户可以通过简单的提示词文本+视频分镜素材,快速且自动的剪辑出高质量的产品营销和泛内容短视频。该项目集成了AI驱动的文案生成、语音合成、视频剪辑、字幕特效等功能,旨在为用户提供开箱即用的短视频制作体验。 核心功能 AI驱动:集成了最新的AI技术,提升视频制作效率和质量 文案生成:基于提示词生成高质量的短视频文案 自动剪辑:支持多种视频格式,自动化批量处理视频剪辑任务 语音合成:将生成的文案转换为自然流畅的语音 字幕特效:自动添加字幕和特效,提升视频质量 批量处理:支持批量任务,按预设自动持续合成视频 多语言支持:支持中文、英文等多种语言,满足不同用户需求 开箱即用:无需复杂配置,用户可以快速上手 持续更新:定期发布新版本,修复bug并添加新功能 安全可靠:完全本地本地化运行,确保用户数据安全 用户友好:简洁直观的用户界面,易于操作 多平台支持:支持Windows、macOS和Linux等多个操作系统
源码来自:https://pan.quark.cn/s/2bb27108fef8 **MetaTrader 5的智能交易系统(EA)**MetaTrader 5(MT5)是由MetaQuotes Software Corp公司研发的一款广受欢迎的外汇交易及金融市场分析软件。 该平台具备高级图表、技术分析工具、自动化交易(借助EA,即Expert Advisor)以及算法交易等多项功能,使交易参与者能够高效且智能化地开展市场活动。 **抛物线SAR(Parabolic SAR)技术指标**抛物线SAR(Stop and Reverse)是由技术分析专家Wells Wilder所设计的一种趋势追踪工具,其目的在于识别价格走势的变动并设定止损及止盈界限。 SAR值的计算依赖于当前价格与前一个周期的SAR数值,随着价格的上扬或下滑,SAR会以一定的加速系数逐渐靠近价格轨迹,一旦价格走势发生逆转,SAR也会迅速调整方向,从而发出交易提示。 **Parabolic SAR EA的操作原理**在MetaTrader 5环境中,Parabolic SAR EA借助内嵌的iSAR工具来执行交易决策。 iSAR工具通过计算得出的SAR位置,辅助EA判断入市与离市时机。 当市场价位触及SAR点时,EA将产生开仓指令,倘若价格持续朝同一方向变动,SAR将同步移动,形成动态止损与止盈参考点。 当价格反向突破SAR时,EA会结束当前仓位并可能建立反向仓位。 **智能交易系统(EA)的优越性**1. **自动化交易**:EA能够持续监控市场,依据既定策略自动完成买卖操作,减少人为情感对交易的影响。 2. **精确操作**:EA依照预设规则操作,无任何迟疑,从而提升交易成效。 3. **风险管控**:借助SA...
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值