二叉树非递归遍历

//前序遍历
class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: Preorder in vector which contains node values.
     */
    vector preorderTraversal(TreeNode *root) {
        // write your code here
        stackstack;
        TreeNode *p = root;
        vectorarray;
        while(!stack.empty() || p) {
            while (p) {
                array.push_back(p->val);
                stack.push(p);
                p = p->left;
            }
            
            if (!stack.empty()) {
                p = stack.top();
                stack.pop();
                p = p->right;
            }
        }
        return array;
    }
};

你可能感兴趣的:(二叉树非递归遍历)