zoukankan      html  css  js  c++  java
  • 二叉搜索树与双向链表

    题目描述:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

    实现语言:Java

    /**
    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
    
        public TreeNode(int val) {
            this.val = val;
        }
    }
    */
    public class Solution {
        public TreeNode Convert(TreeNode root) {
            if(root==null||root.left==null&&root.right==null){
                return root;
            }
            TreeNode left=Convert(root.left);
            TreeNode node=left;
            while(node!=null&&node.right!=null){
                node=node.right;
            }
            if(node!=null){
                node.right=root;
                root.left=node;
            }
            TreeNode right=Convert(root.right);
            if(right!=null){
                root.right=right;
                right.left=root;
            }
            return left!=null?left:root;
        }
    }
    

     实现语言:Java

    /**
    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
    
        public TreeNode(int val) {
            this.val = val;
        }
    }
    */
    import java.util.Stack;
    public class Solution {
        public TreeNode Convert(TreeNode root) {
            if(root==null||root.left==null&&root.right==null){
                return root;
            }
            Stack<TreeNode> stk=new Stack<TreeNode>();
            TreeNode node=null;
            while(root!=null||!stk.isEmpty()){
                if(root!=null){
                    stk.push(root);
                    root=root.right;
                }else{
                    root=stk.pop();
                    if(node==null){
                        node=root;
                    }else{
                        node.left=root;
                        root.right=node;
                        node=root;
                    }
                    root=root.left;
                }
            }
            return node;
        }
    }
    
  • 相关阅读:
    pyinstaller
    screen
    docker
    rsync
    shutil模块
    mysql innodb 理解
    B 树和B+树存储的区别
    B-树原理分析
    mysql 通过mycat 读写分离
    mysql 主从复制
  • 原文地址:https://www.cnblogs.com/xidian2014/p/10197904.html
Copyright © 2011-2022 走看看