[LeetCode]Binary Tree Inorder Traversal
来源:互联网 发布:彩票代购软件 编辑:程序博客网 时间:2024/06/05 11:32
Question
Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree [1,null,2,3]
,
1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
本题难度Medium。有2种算法分别是:递归法和迭代法
【思路】
本题是要对二叉树进行中序遍历。递归法很简单,但迭代法稍微难点。其实迭代法就是把递归法中的第15行与16-17行进行了分离。
1、递归法
【复杂度】
时间 O(N) 空间 O(1)
【代码】
public class Solution { public List<Integer> inorderTraversal(TreeNode root) { //require List<Integer> ans=new LinkedList<>(); //invariant helper(root,ans); //ensure return ans; } private void helper(TreeNode root,List<Integer> ans){ //base case if(root==null) return; helper(root.left,ans); ans.add(root.val); helper(root.right,ans); }}
2、迭代法
【复杂度】
时间 O(N) 空间 O(1)
【注意】
循环条件为:while(root!=null||!stack.isEmpty())
【代码】
public class Solution { public List<Integer> inorderTraversal(TreeNode root) { //require List<Integer> ans=new LinkedList<>(); Stack<TreeNode> stack=new Stack<>(); //invariant while(root!=null||!stack.isEmpty()){ if(root!=null){ stack.push(root);//这两行对应递归法的 root=root.left; // helper(root.left,ans); }else{ root=stack.pop(); //这三行对应递归法的 ans.add(root.val);//ans.add(root.val); root=root.right; //helper(root.right,ans); } } //ensure return ans; }}
参考
Leetcode – Binary Tree Inorder Traversal (Java)
0 0
- LeetCode: Binary Tree Inorder Traversal
- [LeetCode]Binary Tree Inorder Traversal
- LeetCode Binary Tree Inorder Traversal
- [Leetcode] Binary Tree Inorder Traversal
- Leetcode: Binary Tree Inorder Traversal
- LeetCode Binary Tree Inorder Traversal
- LeetCode : Binary Tree Inorder Traversal
- [Leetcode] Binary Tree Inorder Traversal
- 【leetcode】Binary Tree Inorder Traversal
- [LeetCode]Binary Tree Inorder Traversal
- Leetcode: Binary Tree Inorder Traversal
- [leetcode]Binary Tree Inorder Traversal
- LeetCode-Binary Tree Inorder Traversal
- Leetcode Binary Tree Inorder Traversal
- [leetcode] Binary Tree Inorder Traversal
- LeetCode - Binary Tree Inorder Traversal
- [LeetCode] Binary Tree Inorder Traversal
- LeetCode | Binary Tree Inorder Traversal
- IntelliJ IDEA15 简要使用手册
- Flash as 3.0中的函数
- 符号三角形问题(回溯法)
- 紫书第五章
- JNI完全指南(九)——反射
- [LeetCode]Binary Tree Inorder Traversal
- 静态成员函数不可以访问类中的成员变量
- 三级联动android-wheel
- 循环双链表
- php 框架
- Android 中的Binder跨进程通信机制与AIDL
- 关于htmlentities 、htmlspecialchars、addslashes,strip_tags的使用
- poi使用模板导出word带图片
- MYECLIPSE项目导入ECLIPSE中运行