Binary Tree Inorder Traversal
即二叉树的中序遍历。
常见的有两种方法:递归和循环,其中递归调用的栈空间为树的高度,一般为o(logn),循环方式需要开辟一个栈来保存元素,空间复杂度也是o(logn)
tips: 递归比循环耗时,递归:400ms,循环:220ms
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.List;
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
// 非递归
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode curNode = root;
while( !stack.isEmpty() || curNode!=null){
while(curNode != null){
stack.push(curNode);
curNode = curNode.left;
}
if( !stack.isEmpty()){
curNode = stack.pop();
list.add(curNode.val);
curNode = curNode.right;
}
}
return list;
}
/**递归调用
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
inorder(root,list);
return list;
}
public void inorder(TreeNode root,List<Integer> list){
if(root == null)
return;
if(root.left != null){
inorder(root.left,list);
}
list.add(root.val);
// print(root.val);
if(root.right != null){
inorder(root.right,list);
}
}
*/
}