首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。