94.二叉树的中序遍历
2019-05-23 本文已影响0人
皮蛋豆腐酱油
//递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> list = new ArrayList<Integer>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root!=null) {
inorderTraversal(root.left);
list.add(root.val);
inorderTraversal(root.right);
}
return list;
}
}
//非递归
/**
* 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<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
if(root == null) return list;
TreeNode p = root;
while(p != null) {
stack.push(p);
p = p.left;
}
while(!stack.isEmpty()) {
TreeNode q = stack.pop();
list.add(q.val);
TreeNode k = q.right;
while(k != null) {
stack.push(k);
k = k.left;
}
}
return list;
}
}