Binary Tree Inorder Traversal(转)
2015-07-26 23:18
302 查看
Given a binary tree, return the inorder traversal of its nodes' values.
For example: Given binary tree
return
Java代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
dfs(root, res);
return res;
}
private void dfs(TreeNode root, List<Integer> res) {
if (root != null) {
dfs(root.left, res);
res.add(root.val);
dfs(root.right, res);
}
}
}
Java代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
LinkedList<TreeNode> stack = new LinkedList<>();
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;
}
}
http://hcx2013.iteye.com/blog/2230218
For example: Given binary tree
{1,#,2,3},
1 \ 2 / 3
return
[1,3,2].
Java代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
dfs(root, res);
return res;
}
private void dfs(TreeNode root, List<Integer> res) {
if (root != null) {
dfs(root.left, res);
res.add(root.val);
dfs(root.right, res);
}
}
}
Java代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
LinkedList<TreeNode> stack = new LinkedList<>();
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;
}
}
http://hcx2013.iteye.com/blog/2230218
相关文章推荐
- shiro控制登陆成功后跳回之前的页面
- 数据表操作(一)
- UIWebView与JavaScript的交互
- 博客有感
- static_cast, dynamic_cast, reinterpret_cast, const_cast区别
- 风险投资
- TortoiseGit安装过程
- TortoiseGit安装过程
- Key-value存储简介
- HDU 1010 Tempter of the Bone (dfs)
- 黑马程序员--多线程
- Content-disposition
- 微信语音
- Thinkphp3.2 上传详解
- HDU 1237 简单计算器 (栈 )
- 启航
- jQuery攻略
- SIFT局部特征算法
- Token Based Authentication
- [leedcode 144] Binary Tree Preorder Traversal