二叉树的前中后序遍历(栈实现)

class TreeNode{
public:
	TreeNode* leftNode;
	TreeNode* rightNode;
	int val;
	TreeNode(){
		val = 0;
		leftNode = rightNode = NULL;
	}

};
vector preorderTraversal(TreeNode *root) {
	vector vals;
	if (root == NULL) {
		return vals;
	}
	stack ss;
	ss.push(root);
	while (!ss.empty())
	{
		TreeNode* node = ss.top();
		vals.push_back(node->val);
		ss.pop();
		if (node->rightNode)
		{
			ss.push(node->rightNode);
		}
		if (node->leftNode)
		{
			ss.push(node->leftNode);
		}
	}
	return vals;
}

vector inorderTraversal(TreeNode *root) {
	vector vals;
	if (root == NULL) {
		return vals;
	}
	stack ss;
	TreeNode* node = root;
	while (node || !ss.empty())
	{
		while (node)
		{
			ss.push(node);
			node = node->leftNode;
		}
		if (!ss.empty())
		{
			node = ss.top();
			vals.push_back(node->val);
			ss.pop();
			node = node->rightNode;
		}

	}
	return vals;
}

vector postorderTraversal(TreeNode *root) {
	vector result;  
        if(root == NULL) return result;  
          
        stack s;  
        s.push(root);  
          
        while(!s.empty()){  
            TreeNode *n = s.top();  
            result.push_back(n->val);  
            s.pop();  
              
            if(n->left != NULL)  s.push(n->left);  
            if(n->right != NULL) s.push(n->right);  
        }  
          
        reverse(result.begin(), result.end());  
          
        return result;  
}

 

你可能感兴趣的:(数据结构)