现在的位置: 首页 > 综合 > 正文

LeetCode题解:Binary Tree Preorder Traversal

2019年07月24日 ⁄ 综合 ⁄ 共 692字 ⁄ 字号 评论关闭

Binary Tree Preorder Traversal


Given a binary tree, return the preorder traversal 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?

思路:

深度优先搜索用栈进行。

题解:

/**
 * 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) {
        if (root == nullptr)
            return vector<int>();
            
        vector<int> values;
        stack<TreeNode*> visits;
        visits.push(root);
        while(!visits.empty())
        {
            auto node = visits.top();
            visits.pop();
            
            values.push_back(node->val);
            if (node->right) visits.push(node->right);
            if (node->left) visits.push(node->left);
        }
        
        return values;
    }
};

抱歉!评论已关闭.