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]
.
解题思路:
二叉树非递归先序遍历,使用栈来保存被遍历到的,但是还没遍历其右子树的结点。
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> preorderTraversal(TreeNode* root) { 13 vector<int> vals; 14 stack<TreeNode*> nodes; 15 TreeNode* node = root; 16 17 while (node != NULL || !nodes.empty()) { 18 while (node) { 19 nodes.push(node); 20 vals.push_back(node->val); 21 node = node->left; 22 } 23 24 node = nodes.top(); 25 nodes.pop(); 26 node = node->right; 27 } 28 29 return vals; 30 } 31 };
时间: 2024-11-05 14:37:51