zoukankan      html  css  js  c++  java
  • 讲二次搜索树转化为排序的双向链表

    package com.gylhaut.bean;
    
    public class TreeNode<T> {
        public T data;
        public TreeNode left;
        public TreeNode right;
    
        public TreeNode(T data) {
            this.left = null;
            this.right = null;
            this.data = data;
        }
    }
    

     算法实现:

    package com.gylhaut.util;
    
    import com.gylhaut.bean.TreeNode;
    
    public class BinaryTreeHelper {
    
        /**
         * 指向头节点
         * @param root
         * @return
         */
        public static TreeNode convert(TreeNode root){
            root=convert2Link(root);
            while (root.left != null){
                root = root.left;
            }
            return root;
        }
    
        /**
         * 搜索二叉树转成双向链表
         * @param root
         * @return
         */
        public static TreeNode convert2Link(TreeNode root){
            if(root == null|| (root.left == null && root.right == null)){
                return root;
            }
            TreeNode tmp = null;
            if(root.left != null){
               tmp= convert2Link(root.left);
               while (tmp.right != null){
                   tmp = tmp.right;
               }
               tmp.right = root;
               root.left = tmp;
            }
            if (root.right !=null){
                tmp = convert2Link(root.right);
                while (tmp.left != null){
                    tmp = tmp.left;
                }
                tmp.left = root;
                root.right = tmp;
            }
    
            return root;
        }
    
    }
    

      

  • 相关阅读:
    SEO简介
    30个最常用css选择器解析(转自大范甘迪)
    H5新增语义化标签footer
    H5新增语义化标签article
    H5新增语义化标签aside
    H5新增语义化标签figure
    H5新增语义化标签nav
    node 文本替换
    一键生成专题
    node命令行工具—cf-cli
  • 原文地址:https://www.cnblogs.com/gylhaut/p/10270880.html
Copyright © 2011-2022 走看看