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;
}
};
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def solve(self, root, res):
if root is None:
return
self.solve(root.left, res)
res.append(root.val)
self.solve(root.right, res)
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
self.solve(root, res)
return res