码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 144 先序遍历和后序遍历形式一样

时间:2016-08-03 18:27:06      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

这是只写了先序遍历的非递归代码

/**
 * 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>pre_vec;
        stack<TreeNode *>pre_stack;
        TreeNode * NowNode=root;
        while(NowNode||!pre_stack.empty()) {
            if(NowNode!=NULL) {
                pre_stack.push(NowNode);
                pre_vec.push_back(NowNode->val);
                NowNode=NowNode->left;
            }
            else {
                 NowNode=pre_stack.top();
                 pre_stack.pop();
                 NowNode=NowNode->right;
            }
        }
        return pre_vec;
    }
};

 

leetcode 144 先序遍历和后序遍历形式一样

标签:

原文地址:http://www.cnblogs.com/thefirstfeeling/p/5733628.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!