LeetCode144:Binary Tree Preorder Traversal

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

For example:
Given binary tree {1,#,2,3},
这里写图片描写叙述
return [1,2,3].

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

先序遍历应该是三种遍历方式中最好使用非递归来实现的了。
能够每次訪问一个节点后再将其右子节点入栈,然后左子节点入栈。然后再从栈中取元素,能够发现就是先序遍历的结果。

须要注意的是假设子节点不存在就不须要进行入栈操作。


runtime:4ms

/**
 * 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) {
        vector<int> res;
        if(root==NULL)
            return res;
        stack<TreeNode *> s;
        TreeNode * node=root;
        s.push(node);
        while(!s.empty())
        {
            node=s.top();
            s.pop();
            res.push_back(node->val);
            if(node->right)  s.push(node->right);
            if(node->left)  s.push(node->left);
        }
        return res;
    }
};
posted @ 2016-03-09 18:49  blfshiye  阅读(187)  评论(0编辑  收藏  举报