zoukankan      html  css  js  c++  java
  • 刷题感悟

    将二叉查找树转化成双向链表

    题目思路其实不难 ,中序遍历,然后再依次的将数据放入链表中即可

    重点:新加元素前后链的配置 

    有个有意思的地方在于result没有赋初值 导致写代码时需要先初始化 然后删除之 。

    /**
     * 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;
     *     }
     * }
     * Definition for Doubly-ListNode.
     * public class DoublyListNode {
     *     int val;
     *     DoublyListNode next, prev;
     *     DoublyListNode(int val) {
     *         this.val = val;
     *         this.next = this.prev = null;
     *     }
     * }
     */ 
    public class Solution {
        /**
         * @param root: The root of tree
         * @return: the head of doubly list node
         */
        public DoublyListNode bstToDoublyList(TreeNode root) {  
            // Write your code here
            if(root==null)return null;
            DoublyListNode rootsult = new DoublyListNode(0);
            midOrder(root,rootsult);
            rootsult = rootsult.next;
            return rootsult;
        }
        
        public void midOrder(TreeNode root,DoublyListNode result){
            if(root.left!=null)midOrder(root.left,result);
            setNode(root.val, result);
            if(root.right!=null)midOrder(root.right,result);
        }
        public void setNode(int val,DoublyListNode result){
            if(result==null) result = new DoublyListNode(val);
            else{
                DoublyListNode node = new DoublyListNode(val);
                while(result.next!=null)result = result.next;
                node.prev=result;
                result.next = node;
            }
        }
    }

    在大数据量的情况下 有可能会爆栈

    下一步想想如何用非递归的方法实现之 占坑

  • 相关阅读:
    nodejs入门API之http模块
    nodejs入门API之fs模块
    编程官方文档中的方法参数格式的含义
    vs Code编辑器智能提示功能
    nodejs入门之模块
    git的安装与使用
    TypeScript入门九:TypeScript的模块
    TypeScript入门八:TypeScript的命名空间
    TypeScript入门七:TypeScript的枚举
    TypeScript入门六:TypeScript的泛型
  • 原文地址:https://www.cnblogs.com/zslzz/p/7241491.html
Copyright © 2011-2022 走看看