1. 程式人生 > 其它 >劍指offer_二叉搜尋樹與雙向連結串列

劍指offer_二叉搜尋樹與雙向連結串列

技術標籤:演算法連結串列二叉樹資料結構演算法指標

題目
輸入一棵二叉搜尋樹,將該二叉搜尋樹轉換成一個排序的雙向連結串列。要求不能建立任何新的結點,只能調整樹中結點指標的指向。
知識點
二叉樹,搜尋樹,連結串列
思路
最開始:
在這裡插入圖片描述

按照搜尋樹的特性,先中序遍歷,從最左邊開始,按照左子節點,根節點,右子節點的順序,把rightTreeNode從小到大全都串起來。
在這裡插入圖片描述

再從最左下的結點遍歷一遍,設此時pHead為2,temp為3,將temp的左結點變為pHead,並向下遍歷,把所有右結點的左結點修改正確,直到最後temp==null退出迴圈。
在這裡插入圖片描述

程式碼

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution { TreeNode head = null; public TreeNode Convert(TreeNode pRootOfTree) { if(pRootOfTree==null) return null; TreeNode pHead = pRootOfTree; LeftConvert(pRootOfTree); while(pHead.left!=null) pHead = pHead.left; TreeNode headNode = pHead,
tempNode = pHead.right; while(tempNode!=null){ tempNode.left = pHead; tempNode = tempNode.right; pHead = pHead.right; } return headNode; } public void LeftConvert(TreeNode pRootOfTree){ if(pRootOfTree==null) return; Convert
(pRootOfTree.left); if(head==null) head = pRootOfTree; else{ head.right = pRootOfTree; head = head.right;} Convert(pRootOfTree.right); } }