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