首页 > 其他 > 详细

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

时间:2016-08-03 18:25:41      阅读:251      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!