mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 94. Binary Tree Inorder Traversal.md
This commit is contained in:
parent
370360c61a
commit
c1ce0a4ed4
56
solutions/94. Binary Tree Inorder Traversal.md
Normal file
56
solutions/94. Binary Tree Inorder Traversal.md
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
# [94. Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/)
|
||||||
|
# 思路
|
||||||
|
中序遍历二叉树。属于数据结构基本题。
|
||||||
|
## 思路一、递归
|
||||||
|
二叉树的中序、前序、后序遍历最方便的当然就是使用递归了。中序遍历某个节点时,先不访问它,先递归遍历其左子树,然后才访问该节点,最后递归遍历其右节点。
|
||||||
|
|
||||||
|
## 思路二、非递归
|
||||||
|
我们先定义一个栈,然后从根节点开始,进入循环,若当前节点不空那么将其入栈(暂不访问),然后向左下降进入下一循环;若为空则说明往左下降不动了,应该将栈顶元素取出
|
||||||
|
并访问,然后向右下降;循环直到栈空且当前节点也为空为止。
|
||||||
|
|
||||||
|
# C++
|
||||||
|
## 思路一
|
||||||
|
``` C++
|
||||||
|
class Solution {
|
||||||
|
private:
|
||||||
|
void helper(TreeNode* root, vector<int> &res){
|
||||||
|
if(!root) return;
|
||||||
|
helper(root -> left, res);
|
||||||
|
res.push_back(root -> val);
|
||||||
|
helper(root -> right, res);
|
||||||
|
|
||||||
|
}
|
||||||
|
public:
|
||||||
|
vector<int> inorderTraversal(TreeNode* root) {
|
||||||
|
vector<int>res;
|
||||||
|
helper(root, res);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## 思路二
|
||||||
|
``` C++
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
vector<int> inorderTraversal(TreeNode* root) {
|
||||||
|
vector<int>res;
|
||||||
|
if(!root) return res;
|
||||||
|
stack<TreeNode *>stk;
|
||||||
|
TreeNode* p = root;
|
||||||
|
while(!stk.empty() || p){
|
||||||
|
if(p){
|
||||||
|
stk.push(p);
|
||||||
|
p = p -> left; // 一路向左
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
p = stk.top();
|
||||||
|
stk.pop();
|
||||||
|
res.push_back(p -> val);
|
||||||
|
p = p -> right;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in New Issue
Block a user