|

楼主 |
发表于 12-12-2014 08:32 PM
|
显示全部楼层
本帖最后由 MengMa 于 12-12-2014 11:56 PM 编辑
Binary Tree Inorder Traversal
思路1:迭代的
对于当前访问节点root, 如果root不为null, 将该节点push, 同时root = root.left, 这时候如果有左子就持续进栈,直到走到最左侧。如果root == null,可以pop并访问了。需要把root = root.right。这样能让有孩子的右孩子进栈。如果没有孩儿,root变空了,那就继续pop
注意:stack.pop()可以构成2连击。即pop完当前节点后,下次pop要么是这个节点的右子树的根,要么就是这个节点的parent.
复杂度:
时间是O (n), 空间上 O(logn)
- public ArrayList<Integer> inorderTraversal(TreeNode root) {
- ArrayList<Integer> res = new ArrayList<Integer>();
- if(root == null) return res;
- LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
- while(root != null || !stack.isEmpty())
- {
- if(root != null)
- {
- stack.push(root);
- root = root.left;
- }
- else
- {
- root = stack.pop();
- res.add(root.val);
- root = root.right;
- }
- }
- return res;
- }
复制代码
思路2:递归的感觉应该人人都会,所以也没有考得必要吧。
空间复杂度O(logn)时间复杂度O(n)
- public ArrayList<Integer> inorderTraversal(TreeNode root) {
- ArrayList<Integer> res = new ArrayList<Integer>();
- helper(root, res);
- return res;
- }
- private void helper(TreeNode root, ArrayList<Integer> res)
- {
- if(root == null) return;
- helper(root.left, res);
- res.add(root.val);
- helper(root.right, res);
- }
复制代码
|
|