LeetCode:144_Binary Tree Preorder Traversal | 二叉树的前序遍历 | Medium
题目: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:144_Binary Tree Preorder Traversal | 二叉树的前序遍历 | Medium相关推荐
- LeetCode Binary Tree Preorder Traversal(二叉树的前序遍历)
问题:给出一个二叉树,输出前序遍历 思路: 自顶向下遍历过程中,将当前结点的值加入到list中,然后处理左.右子树 具体代码参考: https://github.com/wuli2496/OJ/tre ...
- 144. Binary Tree Preorder Traversal 二叉树的前序遍历
给定一个二叉树,返回它的 前序 遍历. 示例: 输入: [1,null,2,3] 1\2/3 输出: [1,2,3] 进阶: 递归算法很简单,你可以通过迭代算法完成吗? "> 给定一 ...
- [LeetCode] Binary Tree Postorder Traversal 二叉树的后序遍历
Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary ...
- [leetcode] Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values. For example: Given binary t ...
- Leetcode589.N-ary Tree Preorder TraversalN叉树的前序遍历
给定一个 N 叉树,返回其节点值的前序遍历. class Node { public:int val;vector<Node*> children;Node() {}Node(int _v ...
- 【二叉树迭代版前序遍历】LeetCode 144. Binary Tree Preorder Traversal
LeetCode 144. Binary Tree Preorder Traversal Solution1:递归版 二叉树的前序遍历递归版是很简单的,前序遍历的迭代版相对是最容易理解的. 迭代版链接 ...
- 14 二叉树的前序遍历(Binary Tree Preorder Traversal)
文章目录 1 题目 2 描述 3 解决方案 3.1 递归算法 3.1.1 遍历法(Traverse) 思路 源码 3.1.2 分治法(Devide And Conquer) 思路 源码 3.2 非递归 ...
- leetcode 331. Verify Preorder Serialization of a Binary Tree | 331. 验证二叉树的前序序列化(栈解法)
题目 https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ 题解 看了答案,参考:拍案叫绝的两种解 ...
- leetcode 144. Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values. For example: Given binary t ...
最新文章
- 《水泥公司信息管理系统》Access学习心得
- Haunt - Youzan 服务发现 概述
- academic division at cssa
- mock以及特殊场景下对mock数据的处理
- 瞧!公务员的工作还可以这样干
- WordPress 3.0十大看点 CMS功能进一步增强
- Git学习总结(22)——Git 常用操作再总结
- alwayson高可用组_AlwaysOn可用性组–好奇心使您的工作更轻松–第4部分
- 准备离职,工作的一些细节记录
- PCL之常用开源数据集汇总
- 华硕主板前置耳机插孔没有声音怎么办
- 越狱开发笔记(三)——非越狱App砸壳
- 当我们电脑上的Microsoft Office2003/2007/2010无法卸载时怎么处理?
- 最新《java互联网架构师全套课程》附带代码资料(完整)
- Linux下的磁盘分区简介
- 球的表面积公式是怎么推导出来的?
- 数组对象查找某一个对象
- 进制转换(未完待续)
- 测站数据批量脚本下载
- 学大伟业:如何利用课余时间学习物理竞赛,搞定自主招生?