题目 Binary Tree Inorder Traversal
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?
1,递归
/**
* 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> result = new ArrayList<Integer>();
dfs(root,result);
return result;
}
private void dfs(TreeNode root, List<Integer> result){
if(root == null){
return;
}
dfs(root.left,result);
result.add(root.val);
dfs(root.right,result);
}
}
时间复杂度O(n),空间复杂度O(n)
2,使用栈
/**
* 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> result = new ArrayList<Integer>();
if(root == null){
return result;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode tempNode = root;
do{
//左子树不为空,一直入栈
while (tempNode != null){
stack.push(tempNode);
tempNode = tempNode.left;
}
//若左子树为空,则弹出栈顶元素且遍历其右子树
if(!stack.empty()){
TreeNode visitedNode = stack.pop();
result.add(visitedNode.val);
tempNode = visitedNode.right;
}
}while(!stack.empty() || tempNode != null);
return result;
}
}
时间复杂度O(n),空间复杂度O(n)