首页 > 代码库 > LeetCode:Binary Tree Preorder Traversal

LeetCode:Binary Tree Preorder Traversal

题目:Binary Tree Preorder Traversal

二叉树的前序遍历,同样使用栈来解,代码如下:

 1 struct TreeNode { 2     int            val; 3     TreeNode*    left; 4     TreeNode*    right; 5     TreeNode(int x): val(x), left(NULL),right(NULL) {} 6 }; 7  8 vector<int> preorderTraversal(TreeNode *root) //非递归的前序遍历(用栈实现) 9 {10     if (NULL == root) {11         cout << "tree is empty!" << endl;12         exit(0);13     }14 15     TreeNode *pre = root;16     //TreeNode *pTemp = pre;17     stack<TreeNode *> tree_stack;18     vector<int> tree_vector;19     20     tree_stack.push(pre);21     while (!tree_stack.empty()) {22         TreeNode *pTemp = tree_stack.top();23         tree_stack.pop();24 25         tree_vector.push_back(pTemp->val);26         if (pTemp->right != NULL) 27             tree_stack.push(pTemp->right);28         if (pTemp->left != NULL)29             tree_stack.push(pTemp->left);30     }31     return tree_vector;32 }

 

LeetCode:Binary Tree Preorder Traversal