【每日算法】LeetCode 94 —— 二叉树的中序遍历(一百八十六)

题目内容

给定一个二叉树的根节点 root ,返回它的 中序 遍历。

示例

示例 1:

输入:root = [1,null,2,3]
输出:[1,3,2]

示例 2:

输入:root = []
输出:[]

示例 3:

输入:root = [1]
输出:[1]

示例 4:

输入:root = [1,2]
输出:[2,1]

示例 5:

输入:root = [1,null,2]
输出:[1,2]

提示

1、树中节点数目在范围 [0, 100] 内
2、-100 <= Node.val <= 100

题解

中序遍历,即遍历顺序为左子树->根节点->右子树。在实现思路上,有递归和非递归两种实现方法,这里全部给出。

在非递归的实现方法中,用栈来实现针对二叉树的中序遍历。具体思路键代码即可。

代码

//递归实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> ans;
vector<int> inorderTraversal(TreeNode* root) {
dfs(root);
return ans;
}
void dfs(TreeNode* root){
if(!root) return;//当前子树为空,直接返回
dfs(root->left);
ans.push_back(root->val);
dfs(root->right);
}
};

//非递归实现
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;//记录答案
stack<TreeNode*> stk;//栈
while(stk.size()|| root){//当栈不为空,或者节点不为空时
while(root){//当节点不为空,将节点压入栈中,并一直遍历左子树
stk.push(root);
root = root->left;
}
//当栈不为空时,取栈顶元素的值,然后弹出当前节点,并更新当前节点为其右子节点
if(stk.size()){
root = stk.top();
stk.pop();
ans.push_back(root->val);
root = root->right;
}
}
return ans;
}
};
Author: Frederic Niu
Link: https://www.fredericniu.cn/2021/07/07/【每日算法】LeetCode-94-——-二叉树的中序遍历(一百八十六)/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
我的公众号