[leetcode]binary-tree-preorder-Traversal

題目描述:

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

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

實現思路:

要實現非遞歸的二叉樹前序遍歷,可以藉助棧來實現,前序遍歷是根-左-右,先把根壓棧然後彈出到vector中,再依次將右孩子壓棧、左孩子壓棧,然後迭代進行,每次都彈出棧底的結點~

具體實現:

/**
 * Definition for binary tree
 * 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) {
        vector<int> res;
        if(!root){
            return res;
        }
        stack<TreeNode *> st;
        st.push(root);
        while(st.size()){
            TreeNode * temp;
            temp = st.top();
            res.push_back(temp->val);
            st.pop();
            if(temp->right){
                st.push(temp->right);
            }
            if(temp->left){
                st.push(temp->left);
            }
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章