【LeetCode】94. Binary Tree Inorder Traversal 解法及注释
来源:互联网 发布:网络自制剧受众分析 编辑:程序博客网 时间:2024/05/17 04:02
94. Binary Tree Inorder Traversal
Total Accepted: 119866 Total Submissions: 303779 Difficulty: Medium
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
【分析】
这是个二叉树遍历题,涉及遍历为中序遍历(inorder traversal),即左->根->右,有两种解法:
解法一:常规的解法为“递归”,搜索左子树,直到左子树为空,存放当前结点数值,再搜索右子树,对右子树依然采用中序遍历模式,完成后再返回上一层,存放当前结点,在搜索右子树,完成后再返回上一层...到达顶层,即根节点之后,存放根节点,搜索右子树...
解法二:用一个辅助栈空间来存储遍历的结点指针,直到搜索至左子树叶子节点,弹栈,存储当前结点数据域,然后搜索右子树,一直到栈为空,结束,返回。
【解法及注释】
解法一:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<int> inorderTraversal(TreeNode* root) { if(root==NULL)return result; if(root->left!=NULL) { inorderTraversal(root->left); } result.push_back(root->val); if(root->right!=NULL) { inorderTraversal(root->right); } return result; }private: vector<int> result;};
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<int> inorderTraversal(TreeNode* root) { vector<int> result; if(root==NULL)return result; stack<TreeNode*> stk; TreeNode *p=root; while(p!=NULL||!stk.empty()) { if(p!=NULL) { stk.push(p); p=p->left; } else { p=stk.top(); stk.pop(); result.push_back(p->val); p=p->right; } } return result; }};
0 0
- 【LeetCode】94. Binary Tree Inorder Traversal 解法及注释
- Binary Tree Inorder Traversal问题及解法
- LeetCode 94. Binary Tree Inorder Traversal
- [LeetCode]94.Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal Leetcode Python
- [Leetcode] 94. Binary Tree Inorder Traversal
- LeetCode --- 94. Binary Tree Inorder Traversal
- LeetCode 94. Binary Tree Inorder Traversal
- [leetcode] 94.Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal LeetCode
- LeetCode 94. Binary Tree Inorder Traversal
- *LeetCode 94. Binary Tree Inorder Traversal
- [LeetCode]94. Binary Tree Inorder Traversal
- [LeetCode]94. Binary Tree Inorder Traversal
- 【LeetCode】94. Binary Tree Inorder Traversal
- leetcode 94. Binary Tree Inorder Traversal
- leetcode 94. Binary Tree Inorder Traversal
- LeetCode *** 94. Binary Tree Inorder Traversal
- NOJ 1590 大整数阶乘
- Static 关键字
- lightoj 1085
- 数组中的逆序对
- golang了解
- 【LeetCode】94. Binary Tree Inorder Traversal 解法及注释
- 微分学_一元函数最值的求解_蜂房房底结构的设计
- Objective-C Associated Objects 的实现原理
- 继承
- 磁盘读写和数据库读写哪个效率更高?磁盘读写与数据库的关系
- ART中添加 neg.s neg.d 指令及相关代码
- 自定义View<二>
- lua 游戏中数字转字符串的函数
- 【数据结构】Doubly-Linked List双向链表(更新时间:2016-04-13)