【LeetCode】Binary Tree Preorder Traversal

  写迭代实现的实在没什么意思,这里写个用栈实现的吧:

#include <vector>
#include <stack>
#include <algorithm>

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


你可能感兴趣的:(【LeetCode】Binary Tree Preorder Traversal)