1. 程式人生 > >劍指 Offer - 26:二叉搜尋樹與雙向連結串列

劍指 Offer - 26:二叉搜尋樹與雙向連結串列

題目描述

輸入一棵二叉搜尋樹,將該二叉搜尋樹轉換成一個排序的雙向連結串列。要求不能建立任何新的結點,只能調整樹中結點指標的指向

題目連結:https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5

解題思路

解法1:迭代(非遞迴)思路,模擬中序遍歷,記錄上一個遍歷的節點,同當前節點進行雙向指向
解法2:遞迴法

/**
 * 解法1:迭代(非遞迴)法
 */
import java.util.Stack;

public class Solution {
    public TreeNode Convert
(TreeNode pRootOfTree) { if (pRootOfTree == null) return null; Stack<TreeNode> stack = new Stack<>(); TreeNode root = null; TreeNode p = pRootOfTree; TreeNode pre = null; boolean isFirst = true; while (p != null ||
!stack.isEmpty()) { while (p != null) { stack.push(p); p = p.left; } p = stack.pop(); if (isFirst) { root = p; pre = p; isFirst = false; } else { pre.
right = p; p.left = pre; pre = p; } p = p.right; } return root; } }