1. 程式人生 > >LeetCode題解-144. Binary Tree Preorder Traversal(二叉樹的非遞迴前序遍歷)

LeetCode題解-144. Binary Tree Preorder Traversal(二叉樹的非遞迴前序遍歷)

題目:

Given a binary tree, return the preorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,2,3]

思路:

根據前序遍歷訪問的順序,優先訪問根結點,然後再分別訪問左孩子和右孩子。即對於任一結點,其可看做是根結點,因此可以直接訪問,訪問完之後,若其左孩子不為空,按相同規則訪問它的左子樹;當訪問其左子樹時,再訪問它的右子樹。因此其處理過程如下:
對於任一結點P:
     1)訪問結點P,並將結點P入棧;
     2)判斷結點P的左孩子是否為空,若為空,則取棧頂結點並進行出棧操作,並將棧頂結點的右孩子置為當前的結點P,迴圈至1);若不為空,則將P的左孩子置為當前的結點P;

     3)直到P為NULL並且棧為空,則遍歷結束。

程式碼:

/**
 * 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) {
        stack<TreeNode*> S;
        vector<int> res;
        TreeNode* p = root;
        while(p != NULL || !S.empty()){
            while(p!= NULL){
                res.push_back(p->val);
                S.push(p);
                p = p->left;
            }
            if(!S.empty()){
                p = S.top();
                S.pop();
                p = p->right;
            }
        }
        return res;
    }
};