zoukankan      html  css  js  c++  java
  • lintcode:将二叉查找树转换成双链表

    题目

    将一个二叉查找树按照中序遍历转换成双向链表

    给定一个二叉查找树:

        4
       / 
      2   5
     / 
    1   3
    

    返回 1<->2<->3<->4<->5

    解题

    /**
     * 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 Root = new DoublyListNode(root.val);
            if(root.left==null && root.right==null){
                return Root;
            }
            DoublyListNode left = bstToDoublyList(root.left);
            DoublyListNode tmpLeft = left;
            while(tmpLeft!=null && tmpLeft.next!=null){
                tmpLeft = tmpLeft.next;
            }
            if(left!=null){
                tmpLeft.next = Root;
                Root.prev = tmpLeft;
            }
            DoublyListNode right = bstToDoublyList(root.right);
            if(right!=null){
                Root.next = right;
                right.prev = Root;
            }
            return  left!=null?left:Root; 
        }
    }
  • 相关阅读:
    读《构建之法》8、9、10章有感
    评论
    复利计算器(4)——jQuery界面美化、自动补全
    送给搭档的“汉堡”
    MFC之TreeCtrl控件使用经验总结
    MFC绘制图片闪烁详解
    MFC 网络编程中::connect返回-1问题
    C++网络编程之select
    C++关于Condition Variable
    Mutex 和 Lock
  • 原文地址:https://www.cnblogs.com/theskulls/p/5625183.html
Copyright © 2011-2022 走看看