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
return
Note: Recursive solution is trivial, could you do it iteratively?
中序遍历二叉树,递归遍历当然很容易,题目还要求不用递归,下面给出两种方法:
递归:
迭代:
java版本的代码如下所示,首先是递归版本的代码:
再是非递归:
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; } }
相关文章推荐
- iOS学习笔记1(结合项目)---oc的@property属性
- leetcode 297 : Serialize and Deserialize Binary Tree
- Codeforces Round #327 (Div. 2) A. Wizards' Duel
- C语言的编译过程和GCC编译参数
- Light OJ 1032 - Fast Bit Calculations(数位DP)
- BZOJ 1003 ZJOI2006 物流运输trans 动态规划+SPFA
- Codeforces Round #327 (Div. 2)——B. Rebranding
- iphone数据存储之-- Core Data的使用(一)
- codeforces#327-C.Median Smoothing-规律题
- 有关802.11协议
- C++,JAVA之间相互调用学习
- #在蓝懿学习iOS的日子#Day5
- 记使用linux命令行编译c语言步骤
- 局部变量和成员变量的区别
- bfprt算法----找出数组中最小的k个数(Java)
- http状态码详解
- python property
- shell条件判断小知识
- poj 3080(后缀数组)
- document.createElement()的用法