1. 程式人生 > 其它 >JZ36 && Leetcode 426 二叉搜尋樹與雙向連結串列

JZ36 && Leetcode 426 二叉搜尋樹與雙向連結串列

技術標籤:演算法

  • 每次需要想用flag的時候,再想想看有沒有其它的代替方案,會不會那個flag還有其它的很明顯的改變
    比如 pre==null 就相當於找到了
  • 剛開始想到中序遍歷很好,緊接著沒有新的idea。如果這時候,順著中序遍歷走一遍,可能就會發現要實現目標功能,要修改的東西很少很簡單
/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;

    Node() {}

    Node(int _val) {
        val = _val;
        left = NULL;
        right = NULL;
    }

    Node(int _val, Node* _left, Node* _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};

*/
class Solution { public: Node *head, *pre; Node *treeToDoublyList(Node *root) { if(!root) return nullptr; dfs(root); head->left = pre; pre->right = head; return head; } void dfs(Node* cur){ if(cur==nullptr) return ; dfs(cur->
left); if(pre==nullptr) head=cur; else pre->right=cur; cur->left = pre; pre = cur ; dfs(cur->right); } };