zoukankan      html  css  js  c++  java
  • 107. 二叉树的层次遍历 II

    题目描述: 给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
    例如:
    给定二叉树 [3,9,20,null,null,15,7],返回其自底向上的层次遍历为: [ [15,7], [9,20], [3] ]

    • DFS:递归,从上到下遍历二叉树,每一层都是一个结点数组,每次递归都带上结点所在层数就知道该结点该放在哪里了
    //JS
    
    var levelOrderBottom = function(root) {
        let res = [];
        let dfs = (node, depth) => {
            if(!node) return;
            res[depth] = res[depth] || [];
            res[depth].push(node.val);
            dfs(node.left, depth + 1);
            dfs(node.right, depth + 1);
        }
        dfs(root, 0);
        return res.reverse();
    };
    • BFS:层次遍历,可以用单队列也可以用双队列
    //C语言
    //单队列
    //先计算二叉树的高度,得到返回二维数组长度,再正常遍历二叉树,将每层的结点数组从后往前放到结果数组中
    
    #define MAXSIZE 2000
    
    int maxDepth(struct TreeNode* root){
        if(root == NULL) return 0;
        int lDepth = maxDepth(root -> left),
        rDepth = maxDepth(root -> right);
        return 1 + (lDepth > rDepth ? lDepth : rDepth);
    }
    
    int** levelOrderBottom(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
        *returnSize = maxDepth(root);
        if(*returnSize == 0) return NULL;
    
        int **res = (int **)malloc(sizeof(int *) * (*returnSize));
        *returnColumnSizes = (int **)malloc(sizeof(int *) * (*returnSize));
        struct TreeNode *queue[MAXSIZE], *p;
        int rear = 0, front = 0, idx = *returnSize;
        queue[rear++] = root;
        while(front != rear){
            int len = rear - front;
            res[--idx] = (int *)malloc(sizeof(int) * len);
            (*returnColumnSizes)[idx] = len;
            for(int i = 0; i < len; i++){
                p = queue[front++];
                res[idx][i] = p -> val;
                if(p -> left) queue[rear++] = p -> left;
                if(p -> right) queue[rear++] = p -> right;
            }
        }
        return res;
    }
    
    //JS
    var levelOrderBottom = function(root) {
        if(!root) return [];
        let queueArr = [], result = [], node = null;
        queueArr.push(root);
        result.push([root.val]);
    
        while(queueArr.length != 0) {
            let len = queueArr.length, tmpArr = [];
            for(let i = 0; i < len; i++){
                node = queueArr.shift();
                if(node.left) {
                    tmpArr.push(node.left.val);
                    queueArr.push(node.left);
                }
                if(node.right) {
                    tmpArr.push(node.right.val);
                    queueArr.push(node.right);
                }
            }
            if(tmpArr.length != 0)
                result.push(tmpArr);        
        }
        return result.reverse();
    };
    

      

  • 相关阅读:
    对deferred(延迟对象)的理解
    string 、char* 、 char []的转换
    char* 和 cha[]
    层序遍历二叉树
    之字形打印二叉树
    右值
    函数指针(待修改)
    top k

    哈夫曼编码
  • 原文地址:https://www.cnblogs.com/JesseyWang/p/13111760.html
Copyright © 2011-2022 走看看