0
点赞
收藏
分享

微信扫一扫

[leetcode] 94. Binary Tree Inorder Traversal

余寿 2022-08-11 阅读 31


Description

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?

分析

  • 递归的方法很简单,注意终止条件就行了。
  • 非递归版本需要用到栈来模拟,先要遍历到树的最左边,用栈记录回溯的路径,对每一个出栈的元素,检测其右分支,把右分支的左节点压入栈中,把出栈的值押入结果集合中,因为出栈的顺序就是中序遍历的顺序。
  • 如果读者是在不明白,还是老样子,手工对着代码模拟一下啦

代码-递归版

/**
* 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> res;
inorder(root,res);
return res;
}
void inorder(TreeNode* root,vector<int> &res){
if(!root){
return;
}
inorder(root->left,res);
res.push_back(root->val);
inorder(root->right,res);
}
};

代码-非递归版

/**
* 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> inorderTraversal(TreeNode *root) {
vector<int> result;
if(root==NULL){
return result;
}
stack<TreeNode *> s1;
TreeNode *temp=root;
while(!s1.empty()||temp!=NULL){
while(temp){
s1.push(temp);
temp=temp->left;
}

if(!s1.empty()){
temp=s1.top();
s1.pop();
result.push_back(temp->val);
temp=temp->right;
}
}
return result;
}
};

参考文献

​​[编程题]binary-tree-inorder-traversal​​


举报

相关推荐

0 条评论