遞歸轉非遞歸

平面列表

題目描述
給定一個列表,該列表中的每個要素要麼是個列表,要麼是整數。將其變成一個只包含整數的簡單列表。
如果給定的列表中的要素本身也是一個列表,那麼它也可以包含列表。
您在真實的面試中是否遇到過這個題?
樣例
給定 [1,2,[1,2]],返回 [1,2,1,2]。
給定 [4,[3,[2,[1]]]],返回 [4,3,2,1]。
挑戰
請用非遞歸方法嘗試解答這道題。

  • 這題的遞歸解法很簡單, 不貼了. 主要寫寫挑戰內容, 用非遞歸方法解:
    用非遞歸方法解主要是用棧模擬入棧出棧的過程. 根據處理本節點數據的位置可以將此類問題轉換爲二叉樹的前序, 中序, 後序遍歷
    由於三種方法類型的遍歷問題難以記憶, 所以需要依賴一定的規則才能寫對
  1. 處理所有數據,都在出棧時進行處理
  2. 根節點首先入棧再開啓循環
  3. 使用輔助數據結構管理出棧

二叉樹非遞歸方式的遍歷方法與本題的對應

由於本題很特殊,本題的list節點可以認爲對本節點的操作爲空, 所以本題用三種方法解都可以

	public static void preOrderUnRecur(Node head) {
		System.out.print("pre-order: ");
		if (head != null) {
			Stack<Node> stack = new Stack<Node>();
			stack.add(head);
			while (!stack.isEmpty()) {
				head = stack.pop();
				System.out.print(head.value + " ");
				if (head.right != null) {
					stack.push(head.right);
				}
				if (head.left != null) {
					stack.push(head.left);
				}
			}
		}
		System.out.println();
	}

可以看到, 先序的處理最簡單

  1. 從棧中彈出一個, 處理
  2. 將右子樹入棧
  3. 將左子樹入棧
  4. 循環到棧空

先壓右子樹, 就可以保證棧頂的是左子樹.

用這種思路來處理本題可以寫出如下AC代碼

public class Solution {

    // @param nestedList a list of NestedInteger
    // @return a list of integer
    public List<Integer> flatten(List<NestedInteger> nestedList) {
        // Write your code here
        List<Integer> re = new ArrayList<>();
        for (int i = 0; i < nestedList.size(); ++i) {
            flatternMyself(nestedList.get(i),re);
        }
        return re;
    }

    void flatternMyself(NestedInteger integer,List<Integer> container) {
        Stack<NestedInteger> nesStack = new Stack<>();
        nesStack.push(integer); //根節點入棧
        Stack<NestedInteger> helpStack = new Stack<>();
        while (!nesStack.empty()) {
            //出棧一個節點進行處理
            NestedInteger tempInt = nesStack.pop();
            if (tempInt != null) {
                if (tempInt.isInteger()) {
                    container.add(tempInt.getInteger());
                } else {
                    // container.add(-1);
                }

                if (tempInt.isInteger()) {
                    nesStack.push(null);
                } else {
                    List<NestedInteger> tempList = tempInt.getList();
                    for (int i = tempList.size() - 1; i >= 0; i--) {
                        nesStack.add(tempList.get(i));
                    }
                }
            }
        }
    }
}
	public static void inOrderUnRecur(Node head) {
		System.out.print("in-order: ");
		if (head != null) {
			Stack<Node> stack = new Stack<Node>();
			while (!stack.isEmpty() || head != null) {
				if (head != null) {
					stack.push(head);
					head = head.left;
				} else {
					head = stack.pop();
					System.out.print(head.value + " ");
					head = head.right;
				}
			}
		}
		System.out.println();
	}

中序遍歷的思路主要是, 先一路壓左, 對應遞歸寫法一上來直接遞歸左子樹. 壓到空, 對應葉子節點, 然後出棧處理本節點, 再壓右.

如果不使用上述寫法, 使用兩層while寫法, 一定要把空指針入棧, 不循環壓左子樹的時候, 無法知道當前節點是第一次遇到, 還是左子樹已經壓過, 從左子樹回來之後遇到的.
如下 :

class Solution {
public:
    vector<int> inorderTraversal(TreeNode * root) {
        // write your code here
        vector<int> ans;
        if (root == nullptr) {
            return ans;
        }
        stack<TreeNode *> nes;
        nes.push(root);
        while (!nes.empty()) {
            while (nes.top() != nullptr) {
                nes.push(nes.top()->left);
            }
            nes.pop();
            // 如果頭節點沒有右子樹, 可能出現棧中只有一個null的情況, 上面pop以後, 這裏可能就會empty, 所以要判斷一下
            // 但是這裏不用判斷棧頂, 因爲不可能出現連續有兩個null的情況
            // 因爲遇到一個空以後, 就不會push, 然後就將空pop了
            if (!nes.empty()) {
                TreeNode *pNode = nes.top();
                nes.pop();
                ans.push_back(pNode->val);
                nes.push(pNode->right);
            }
        }
        return ans;
    }
};

這種寫法的處理對應本題需要在class中增加一個mark以便在壓入右子樹的時候,找到當前list的下一個應該被壓的節點. OJ太傻, 所以本題這種寫法暫時不做, 意會就行

	public static void posOrderUnRecur1(Node head) {
		System.out.print("pos-order: ");
		if (head != null) {
			Stack<Node> s1 = new Stack<Node>();
			Stack<Node> s2 = new Stack<Node>();
			s1.push(head);
			while (!s1.isEmpty()) {
				head = s1.pop();
				s2.push(head);
				if (head.left != null) {
					s1.push(head.left);
				}
				if (head.right != null) {
					s1.push(head.right);
				}
			}
			while (!s2.isEmpty()) {
				System.out.print(s2.pop().value + " ");
			}
		}
		System.out.println();
	}

後序第一種寫法, 用一個輔助棧, 將先序的順序調整爲後序, 關鍵還是在出棧時處理數據

可寫出如下AC代碼

public class Solution {

    // @param nestedList a list of NestedInteger
    // @return a list of integer
    public List<Integer> flatten(List<NestedInteger> nestedList) {
        // Write your code here
        List<Integer> re = new ArrayList<>();
        for (int i = 0; i < nestedList.size(); ++i) {
            flatternMyself(nestedList.get(i),re);
        }
        return re;
    }

    void flatternMyself(NestedInteger integer,List<Integer> container) {
        Stack<NestedInteger> nesStack = new Stack<>();
        nesStack.push(integer); //根節點入棧
        Stack<Integer> helpStack = new Stack<>();
        while (!nesStack.empty()) {
            //出棧一個節點進行處理
            NestedInteger tempInt = nesStack.pop();
            if (tempInt != null) {
                if (tempInt.isInteger()) {
                    helpStack.push(tempInt.getInteger());
                } else {
                    // container.add(-1);
                }

                if (tempInt.isInteger()) {
                    nesStack.push(null);
                } else {
                    List<NestedInteger> tempList = tempInt.getList();
                    for (int i = 0; i <tempList.size(); i++) {
                        nesStack.push(tempList.get(i));
                    }
                }
            }
        }
        while (!helpStack.empty()) {
            container.add(helpStack.pop());
        }
    }
}
	public static void posOrderUnRecur2(Node h) {
		System.out.print("pos-order: ");
		if (h != null) {
			Stack<Node> stack = new Stack<Node>();
			stack.push(h);
			Node c = null;
			while (!stack.isEmpty()) {
				c = stack.peek();
				if (c.left != null && h != c.left && h != c.right) {
					stack.push(c.left);
				} else if (c.right != null && h != c.right) {
					stack.push(c.right);
				} else {
					System.out.print(stack.pop().value + " ");
					h = c;
				}
			}
		}
		System.out.println();
	}

後序第二種

快排的非遞歸寫法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章