0
点赞
收藏
分享

微信扫一扫

94. Binary Tree Inorder Traversal**

94. Binary Tree Inorder Traversal**

​​https://leetcode.com/problems/binary-tree-inorder-traversal/​​

题目描述

Given a binary tree, return the inorder traversal of its nodes’ values.

Example:

Input: [1,null,2,3]
1
\
2
/
3

Output: [1,3,2]

Follow up: Recursive solution is trivial, could you do it iteratively?

C++ 实现 1

递归.

class Solution {
private:
vector<int> res;
void inorder(TreeNode *root) {
if (!root) return;
inorder(root->left);
res.push_back(root->val);
inorder(root->right);
}
public:
vector<int> inorderTraversal(TreeNode* root) {
inorder(root);
return res;
}
};

C++ 实现 2

中序遍历的迭代形式. 建议对照 144. Binary Tree Preorder Traversal** 一起看, 容易发现共性. 为了方便解析, 先给出所有的代码:

class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
if (!root) return {};
vector<int> res;
stack<TreeNode*> st;
TreeNode *p = root;
while (!st.empty() || p) {
if (p) {
st.push(p);
p = p->left;
} else {
auto cur = st.top();
st.pop();
res.push_back(cur->val);
p = cur->right;
}
}
return res;
}
};

其中用 ​​p​​​ 来指向当前访问的节点. 如果把 ​​while​​ 中的部分抽离出来并去除有关栈的部分进行观察, 并和递归的形式进行对照:

if (p) {
p = p->left;
} else {
res.push_back(cur->val);
p = cur->right;
}

可以发现和递归的形式相似. 栈用来保存每一次访问节点的状态, 如果 ​​p​​​ 存在, 那么将节点当前状态保存到栈中, 只有当 ​​p​​​ 不存在时, 表示左子树访问完, 需要从栈中恢复 root 节点的状态, ​​p​​ 要继续访问右子树.

if (p) {
st.push(p);
p = p->left;
} else {
auto cur = st.top();
st.pop();
res.push_back(cur->val);
p = cur->right;
}


举报

相关推荐

0 条评论