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?
中序遍历二叉树,递归遍历当然很容易,题目还要求不用递归,下面给出两种方法:
递归:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> inorderTraversal(TreeNode* root) { 13 if(!root) return ret; 14 tranverse(root); 15 return ret; 16 } 17 18 void tranverse(TreeNode * root) 19 { 20 if(!root) return; 21 tranverse(root->left); 22 ret.push_back(root->val); 23 tranverse(root->right); 24 } 25 private: 26 vector<int> ret; 27 };
迭代:
1 class Solution { 2 public: 3 vector<int> inorderTraversal(TreeNode* root) { 4 vector<int> ret; 5 if(!root) return ret; 6 map<TreeNode *, bool> m; 7 stack<TreeNode *> s; 8 s.push(root); 9 while(!s.empty()){ 10 TreeNode * t = s.top(); 11 if(t->left && !m[t->left]){ 12 m[t->left] = true; 13 s.push(t->left); 14 t = t->left; 15 continue; 16 } 17 ret.push_back(t->val); 18 s.pop(); 19 if(t->right && !m[t->right]){ 20 m[t->right] = true; 21 s.push(t->right); 22 t = t->right; 23 } 24 } 25 return ret; 26 } 27 };
java版本的代码如下所示,首先是递归版本的代码:
1 public class Solution { 2 public List<Integer> inorderTraversal(TreeNode root) { 3 List<Integer> list = new ArrayList<Integer>(); 4 recur(list, root); 5 return list; 6 } 7 8 public void recur(List<Integer> list, TreeNode root){ 9 if(root == null) 10 return; 11 if(root.left != null) 12 recur(list, root.left); 13 list.add(root.val); 14 if(root.right != null) 15 recur(list, root.right); 16 } 17 }
再是非递归:
1 public class Solution { 2 public List<Integer> inorderTraversal(TreeNode root) { 3 Stack<TreeNode> s = new Stack<TreeNode>(); 4 List<Integer> l = new ArrayList<Integer>(); 5 Map<TreeNode, Integer> m = new HashMap<TreeNode, Integer>(); 6 if(root != null) 7 s.push(root); 8 while(!s.empty()){ 9 TreeNode t = s.peek(); 10 while(t.left != null && !m.containsKey(t.left)){ 11 s.push(t.left); 12 m.put(t.left, 1); 13 t = t.left; 14 } 15 s.pop(); 16 l.add(t.val); 17 if(t.right != null && !m.containsKey(t.right)){ 18 s.push(t.right); 19 m.put(t.right, 1); 20 } 21 } 22 return l; 23 } 24 }