算法系列——Binary Tree Inorder Traversal
来源:互联网 发布:简述js的事件委托 编辑:程序博客网 时间:2024/06/16 07:44
题目描述
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?
解题思路
两种方法,递归法和非递归法。实现思路和Binary Tree Preorder Traversal 类似。
程序实现
递归
public class Solution { private List<Integer> result=new ArrayList<Integer>(); public List<Integer> inorderTraversal(TreeNode root) { if(root==null) return result; inorder(root); return result; } private void inorder(TreeNode root){ if(root==null) return ; inorder(root.left); result.add(root.val); inorder(root.right); }}
非递归
public class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> result=new ArrayList<Integer>(); if(root==null) return result; Stack<Command> stack=new Stack<Command>(); stack.push(new Command("go",root)); while(!stack.isEmpty()){ Command command=stack.pop(); if("print".equals(command.s)) result.add(command.node.val); else{ if(command.node.right!=null) stack.push(new Command("go",command.node.right)); stack.push(new Command("print",command.node)); if(command.node.left!=null) stack.push(new Command("go",command.node.left)); } } return result; }}class Command{ String s; TreeNode node; Command(String s,TreeNode node){ this.s=s; this.node=node; }}
阅读全文
0 0
- 算法系列——Binary Tree Inorder Traversal
- LeetCode——Binary Tree Inorder Traversal
- LeetCode——Binary Tree Inorder Traversal
- LeetCode94——Binary Tree Inorder Traversal
- LeetCode94——Binary Tree Inorder Traversal
- Leetcode94——Binary Tree Inorder Traversal
- 【Leetcode长征系列】Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- 自定义Toast工具类
- DataGridView列自适应宽度
- python06字典
- hive基本操作
- spring整合应用安全框架Shiro
- 算法系列——Binary Tree Inorder Traversal
- VIM常用编辑命令
- multipath -ll输出结果中2:0:0:15的解释
- mybatis(9)--输入映射
- css样式以及种类
- lamp下安装zabbix
- 机器学习之K-近邻算法
- 学习js正则表达式
- poj3580:SuperMemo(块状链表/Splay)