1. 程式人生 > >LeetCode 144 Binary Tree Preorder Traversal(二叉樹前序遍歷)

LeetCode 144 Binary Tree Preorder Traversal(二叉樹前序遍歷)

Given a binary tree, return thepreordertraversal of its nodes' values.

For example:
Given binary tree{1,#,2,3},

   1
    \
     2
    /
   3

return[1,2,3].

Note:Recursive solution is trivial, could you do it iteratively?

題目大意:寫出二叉樹的非遞迴前序遍歷的方法。

解題思路:和中序遍歷的那一道題類似,處理過程如下:

    對於任意節點N:

    1. 訪問N並將N入棧

    2. 判斷結點N的左孩子是否為空,若為空,則取棧頂結點並進行出棧操作,並將棧頂結點的右孩子置為當前結點N,迴圈至1;若不為空,則將N的左孩子置為當前結點N

    3. 直到N為空且棧也為空,遍歷結束

參考資料:http://www.cnblogs.com/dolphin0520/archive/2011/08/25/2153720.html

程式碼如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        if(root == nullptr) return vector<int>();
        
        stack<TreeNode*> stk;
        vector<int> ans;
        TreeNode* now = root;
        
        while(now || stk.size()){
            while(now){
                stk.push(now);
                ans.push_back(now->val);
                now = now->left;
            }
            
            if(stk.size()){
                now = stk.top();
                stk.pop();
                now = now->right;
            }
        }
        return ans;
    }
};