144. Binary Tree Preorder Traversal

144. Binary Tree Preorder Traversal

题目

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

For example:
Given binary tree [1,null,2,3],

   1
    
     2
    /
   3

return [1,2,3].

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

非递归实现二叉树的后序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

//preorder tranversal
class Solution {
public:
	vector<int> preorderTraversal(TreeNode *root) {
		vector<int> vec;
		stack<TreeNode*> sta;
		if (root)
		{
			/*vec.push_back(root->val);
			sta.push(root);
			root = root->left;*/
			while (root||!sta.empty()) // && bug1  //树不为空或者栈不为空,继续循环
			{
				while (root)
				{
					vec.push_back(root->val); //第一次遍历根节点
					sta.push(root);
					root = root->left;
				}
				if (!sta.empty())
				{
					TreeNode* temp = sta.top();
					sta.pop();
					root = temp->right;
				}
			}
		}
		return vec;
	}
};

144. Binary Tree Preorder Traversal

原文地址:https://www.cnblogs.com/ranjiewen/p/8080933.html