您的位置:首页 > 其它

LeetCode OJ:Binary Tree Inorder Traversal(中序遍历二叉树)

2015-10-26 19:26 525 查看
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 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) {
if(!root) return ret;
tranverse(root);
return ret;
}

void tranverse(TreeNode * root)
{
if(!root) return;
tranverse(root->left);
ret.push_back(root->val);
tranverse(root->right);
}
private:
vector<int> ret;
};


迭代:

class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ret;
if(!root) return ret;
map<TreeNode *, bool> m;
stack<TreeNode *> s;
s.push(root);
while(!s.empty()){
TreeNode * t = s.top();
if(t->left && !m[t->left]){
m[t->left] = true;
s.push(t->left);
t = t->left;
continue;
}
ret.push_back(t->val);
s.pop();
if(t->right && !m[t->right]){
m[t->right] = true;
s.push(t->right);
t = t->right;
}
}
return ret;
}
};


java版本的代码如下所示,首先是递归版本的代码:

public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
recur(list, root);
return list;
}

public void recur(List<Integer> list, TreeNode root){
if(root == null)
return;
if(root.left != null)
recur(list, root.left);
list.add(root.val);
if(root.right != null)
recur(list, root.right);
}
}


再是非递归:

public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> s = new Stack<TreeNode>();
List<Integer> l = new ArrayList<Integer>();
Map<TreeNode, Integer> m = new HashMap<TreeNode, Integer>();
if(root != null)
s.push(root);
while(!s.empty()){
TreeNode t = s.peek();
while(t.left != null && !m.containsKey(t.left)){
s.push(t.left);
m.put(t.left, 1);
t = t.left;
}
s.pop();
l.add(t.val);
if(t.right != null && !m.containsKey(t.right)){
s.push(t.right);
m.put(t.right, 1);
}
}
return l;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: