[leetcode] Binary Tree Preorder Traversal 非递归先序遍历
来源:互联网 发布:店宝宝实物软件 编辑:程序博客网 时间:2024/05/21 14:06
Binary Tree Preorder Traversal
Total Accepted: 20397 Total Submissions: 58308My SubmissionsGiven 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]
.
Note: Recursive solution is trivial, could you do it iteratively?
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<int> preorderTraversal(TreeNode *root) { vector<int> result; if(root==NULL) return result; stack<TreeNode *> mstack;//堆栈模拟递归 mstack.push(root); while(!mstack.empty()) { TreeNode * top = mstack.top(); if(mstack.top()!=NULL) { result.push_back(mstack.top()->val); mstack.pop(); } //注意,先右边,仔细体会 if(top->right!=NULL) { mstack.push(top->right); } if(top->left!=NULL) { mstack.push(top->left); } } return result; }};
0 0
- [leetcode] Binary Tree Preorder Traversal 非递归先序遍历
- 【leetcode】非递归先序遍历二叉树(Binary Tree Preorder Traversal)
- [LeetCode] Binary Tree Preorder Traversal (非递归的先序遍历)
- LeetCode Binary Tree Preorder Traversal (二叉树先序遍历非递归)
- Binary Tree Preorder Traversal 二叉树的先序遍历,使用堆栈,非递归
- 【leetcode 先序遍历】Binary Tree Preorder Traversal
- [C++]LeetCode: 95 Binary Tree Preorder Traversal (先序遍历)
- leetcode:Binary Tree Preorder Traversal 先序遍历
- LeetCode Binary Tree Preorder Traversal 前序遍历二叉树 递归和非递归解法
- leetcode 144. Binary Tree Preorder Traversal-前序遍历|递归|非递归
- Binary Tree Preorder Traversal -先序遍历
- LeetCode 144. Binary Tree Preorder Traversal (前序遍历的非递归实现)
- LeetCode:Binary Tree Preorder Traversal(非递归方法前序遍历二叉树)
- 【Leetcode】144. Binary Tree Preorder Traversal 【Tree】【递归&&非递归】
- 【LeetCode】Binary Tree Preorder Traversal 二叉树前序遍历递归以及非递归算法
- 【LeetCode】144. Binary Tree Preorder Traversal 二叉树先序遍历的非递归实现
- LeetCode 144. Binary Tree Preorder Traversal (二叉树先根序遍历,非递归)
- 144. Binary Tree Preorder Traversal 【先序遍历 + 栈模拟递归】
- method 与 function的区别
- 【推荐】.NET使用NPOI组件将数据导出Excel
- 设计模式之单例模式
- JAVA Timer 分析
- 日历问题
- [leetcode] Binary Tree Preorder Traversal 非递归先序遍历
- 小波变换 通俗解读(2)
- JAVA的ThreadLocal
- PHP str_replace() 函数
- git教程
- 算法课第7周作业——背包问题
- 鸡兔同笼
- 第1次实验——NPC问题(回溯算法、聚类分析).....
- 补第七周作业