LeetCode94 Binary Tree Inorder Traversal
问题来源LeetCode94
问题描述
Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3return [1,3,2].
Recursive solution is trivial, could you do it iteratively?
问题分析
这道题是很简单的二叉树的中序遍历,最常用的就是递归实现,但是这道题后面建议尝试迭代方案。那么在这里就提供两种方案好了。迭代方案就是使用Stack来实现就可以了。
代码如下
递归代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list =new ArrayList<>();
help(list,root);
return list;
}
private void help(List<Integer> list,TreeNode treeNode){
if(treeNode==null){
return;
}
//遍历left
help(list,treeNode.left);
//根节点
list.add(treeNode.val);
help(list,treeNode.right);
}
}
迭代代码实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new LinkedList<>();
TreeNode curr = root, prev = null;
while(curr != null) {
if(curr.left == null) {
result.add(curr.val);
curr = curr.right;
} else {
prev = curr.left;
while(prev.right != null && prev.right != curr)
prev = prev.right;
if(prev.right == null) {
prev.right = curr;
curr = curr.left;
} else {
result.add(curr.val);
prev.right = null;
curr = curr.right;
}
}
}
return result;
}
}
LeetCode学习笔记持续更新
GitHub地址 https://github.com/yanqinghe/leetcode
CSDN博客地址 http://blog.csdn.net/yanqinghe123/article/category/7176678