给定一个二叉树,返回它的中序 遍历。
示例:
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
递归:
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
result.addAll(inorderTraversal(root.left));
result.add(root.val);
result.addAll(inorderTraversal(root.right));
return result;
}
非递归:
/**
* 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 ArrayList<>();
if (root == null) {
return result;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode curNode = root;
while (!stack.isEmpty() || curNode != null) {
if (curNode != null) {
stack.push(curNode);
curNode = curNode.left;
} else {
curNode = stack.pop();
result.add(curNode.val);
curNode = curNode.right;
}
}
return result;
}
}