Given a binary tree, return the preorder traversal of its nodes‘ values.
For example:
Given binary tree {1,#,2,3}
,
1 2 / 3
return [1,2,3]
.
#include<iostream> #include<vector> #include<stack> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; //先序遍历 vector<int> preorderTraversal(TreeNode *root) { vector<int>ResultVectorPsotorder; stack<TreeNode*>StackNode; if (root == NULL) return ResultVectorPsotorder; StackNode.push(root); TreeNode*CurNode = NULL; while (!StackNode.empty()) { CurNode = StackNode.top(); ResultVectorPsotorder.push_back(CurNode->val); StackNode.pop(); if (CurNode->right) StackNode.push(CurNode->right); if (CurNode->left) StackNode.push(CurNode->left); } return ResultVectorPsotorder; }
Binary Tree Preorder Traversal
原文:http://blog.csdn.net/li_chihang/article/details/43562839