给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
思路:使用迭代算法需要利用栈来解决,根据中序遍历的规则,需要从根结点开始,一直寻找左结点,直到没有左结点为止,利用栈的原理将结点加入到集合中,接着处理右结点即可。
解法一(递归):
/**
* 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<>();
public List<Integer> inorderTraversal(TreeNode root) {
ldr(root);
return list;
}
private void ldr(TreeNode root){
if(root == null){
return;
}
ldr(root.left);
list.add(root.val);
ldr(root.right);
}
}
解法二(迭代):
/**
* 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) {
ldr(root);
return list;
}
private void ldr(TreeNode root){
Stack<TreeNode> stack = new Stack<TreeNode>();
while(root != null || !stack.isEmpty()){
while(root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
list.add(root.val);
root = root.right;
}
}
}
补充:
前序遍历:根节点→左子树→右子树(根节点在前)
中序遍历:左子树→根节点→右子树(根节点在中间)
后序遍历:左子树→右子树→根节点(根节点在后)