Leetcode - Convert a given Binary Tree to Doubly Linked List

这不是一个Leetcode 题目.我自己写了下。
题意如下:
Convert a binary search tree to a sorted, circular, doubly-linked list, in place (using the tree nodes as the new list nodes).

use leftChild as "prev"

use rightChild as "next

My code:

import java.util.Comparator;
import java.util.PriorityQueue;

public class Solution {
    public TreeNode traverse(TreeNode root) {
        if (root == null)
            return null;
        return dfs(root)[0];
    }
    
    private TreeNode[] dfs(TreeNode root) {
        if (root == null)
            return null;
        TreeNode[] left = dfs(root.left);
        TreeNode head = null;
        TreeNode tail = null;
        if (left != null) {
            head = left[0];
            left[1].right = root;
            root.left = left[1];
        }
        TreeNode[] right = dfs(root.right);
        if (right != null) {
            root.right = right[0];
            right[0].left = root;
            tail = right[1];
        }
        TreeNode[] ret = new TreeNode[2];
        ret[0] = (head == null ? root : head);
        ret[1] = (tail == null ? root : tail);
        return ret;
    }
    
    
    
    public static void main(String[] args) {
        Solution test = new Solution();
        TreeNode a1 = new TreeNode(1);
        TreeNode a2 = new TreeNode(2);
        TreeNode a3 = new TreeNode(3);
        TreeNode a4 = new TreeNode(4);
        TreeNode a5 = new TreeNode(5);
        TreeNode a6 = new TreeNode(6);
        TreeNode a7 = new TreeNode(7);
        a1.left = a2;
        a1.right = a3;
        a2.left = a4;
        a2.right = a5;
        a3.left = a6;
        a3.right = a7;
        TreeNode head = test.traverse(a1);
        TreeNode tail = null;
        while (head.right != null) {
            System.out.println(head.val);
            head = head.right;
        }
        System.out.println(head.val);
        tail = head;    
        System.out.println("**************");
        while (tail != null) {
            System.out.println(tail.val);
            tail = tail.left;
        }
    }
}

自己测试了下。感觉差不多了。其实就是一个简单的dfs,in order traverse this tree.
然后每次返回一个数组,第一位放head of sub tree, 第二位放tail of sub tree
然后注意双向链表的连接。

Anyway, Good luck, Richardo!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,771评论 0 33
  • 因为什么,你如此平凡。 一个人的时候我总是这样问自己。 灯影摇曳,烛光映在漆黑的夜里。有温暖的光温暖这样的夜。夜风...
    xinmenglinlin阅读 401评论 0 0
  • 1. 生活中你是否有例过下列计划:我从现在开始要每天写日记,每天跑步3-5公里,每天朗读英语10分钟……诸如此类计...
    赋能姐在行动阅读 300评论 0 1
  • 定义格式int[] a;定义一个int类型的数组a变量int a[];定义一个int类型的a数组变量推荐第一种。 ...
    Yix1a阅读 254评论 0 0
  • 关于295社作业要求及解读 一.题材:立冬 “立冬”是二十四节气之一,作为题材,不要求单纯地去描写...
    诗词海棠阅读 447评论 0 4