题目
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
思路
递归方法
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> myvector;
inorder(root,myvector);
return myvector;
}
void inorder(TreeNode *root, vector<int> &myvector)
{
if(!root)
return ;
inorder(root->left,myvector);
myvector.push_back(root->val);
inorder(root->right,myvector);
}
};
迭代方法
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> myvector;
stack<TreeNode *> mystack;
while(!mystack.empty() || root!=NULL)
{
while(root)
{
mystack.push(root);
root = root->left;
}
if(!mystack.empty())
{
root = mystack.top();
mystack.pop();
myvector.push_back(root->val);
root = root->right;
}
}
return myvector;
}
};
最新 java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
if(root == null){
return result;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = root;
// while(p != null || !stack.empty()){
// while(p != null){
// stack.push(p);
// p = p.left;
// }
// if(!stack.empty()){
// p = stack.pop();
// result.add(p.val);
// stack.push(p.right);
// }
// }
while(p != null || !stack.empty()){
if(p != null){
stack.push(p);
p = p.left;
} else {
TreeNode t = stack.pop();
result.add(t.val);
p = t.right;
}
}
return result;
}
}上述第一种超时。。。
本文对比了递归和迭代两种方法实现二叉树的中序遍历,并通过实例代码展示如何进行操作。强调了在不同场景下选择合适的方法以提高效率。
364

被折叠的 条评论
为什么被折叠?



