难度:中等

    题目描述:
    给定一个二叉树,返回它的中序 遍历。
    image.png
    示例:

    1. 输入: [1,null,2,3]
    2. 1
    3. \
    4. 2
    5. /
    6. 3
    7. 输出: [1,3,2]

    解题思路:
    递归法:

    1. var inorderTraversal = function(root) {
    2. let result = [];
    3. const pushRoot = (root) => {
    4. if(root!==null){
    5. if(root.left != null){
    6. pushRoot(root.left);
    7. }
    8. result.push(root.val);
    9. if(root.right !=null){
    10. pushRoot(root.right);
    11. }
    12. }
    13. }
    14. pushRoot(root);
    15. return result;
    16. };

    迭代法:
    中序遍历,先要将最左边的节点全部加入栈中,然后逐个pop出来
    核心思想注意,将右子树重置为root,进行下一步的循环。

    两个while嵌套,中间的就是继续存放子树的节点

    var inorderTraversal = function(root) {
        let arr = []
        let stackArr = []
        while(root!=null || stackArr.length!=0){
    
            while(root!=null){
                stackArr.push(root)
                root = root.left
            }
            root = stackArr.pop()
            arr.push(root.val)
            root = root.right
        }
        return arr
    };