2021.9.24-dfs和bfs所涉及的问题

遍历二叉树所能求得的属性

  • 通过先序 or 中序 or 后序 or 层序(BFS 和 DFS)遍历 方式能求的一棵树的 深度路径判断二叉树是否对称,平衡等叶子节点之和 等属性

自底到顶 DFS & 自顶到底 BFS

110.平衡二叉树

  • 110.平衡二叉树
    • 自低到顶 为此题最优解法
    • 分别递归左右子树
      • 若左右子树高度差大于1,则返回-1
      • 否则返回以该根节点的左右子树高度差
    var isBalanced = function(root) {
    	function recur(node) {
    		if (!root) return 0;
    		
    		let leftDepth = recur(node.left);
    		if (leftDepth == -1) return -1;
    		let rightDepth = recur(node.right);
    		if (rightDepth == -1) return -1;
    
    		return Math.abs(leftDepth - rightDepth) < 2 ? Math.max(leftDepth,rightDepth) + 1 : -1;
    	}
    	return recur(root) != -1;
    }
    

104.二叉树的最大深度

  • 104.二叉树的最大深度
    • 利用DFS或BFS遍历二叉树的同时,记录最大深度即可
    // 1. 递归DFS,自低向上
    var maxDepth = function(root) {
    	function maxRaceDepth (node,level) {
            if (!node) return 0;
            return Math.max(maxRaceDepth(node.left,level),maxRaceDepth(node.right,level)) + 1;
        }
    	return maxRaceDepth(root,0);
    }
    
    	// 2. 迭代实现BFS,自顶向低
    	var maxDepth = function(root) {
    	
    	    let queue = [];
    	    if (root) queue.push(root);
    	    
    	    while (queue.length > 0) {
    	        let levelSize = queue.length;
    	        for (let i = 0; i < levelSize; i ++) {
    	            let node = queue.shift();
    	            node.left && queue.push(node.left);
    	            node.right && queue.push(node.right);
    	        }
    	        maxRoot ++;
    	    }
    	    
    	    return maxRoot;
    	}
    

111.二叉树的最小深度

var minDepth = function(root) {
    // 特殊情况
    if (!root) return 0;

    // 1. 递归DFS,寻找最小深度
    // let min = 2 ** 32 - 1;
    // function minRaceDepth (node,level) {
    //     // 终止条件: 叶子节点
    //     if (!node.left && !node.right) {
    //         min = Math.min(min,level);
    //         return;
    //     }
    //     node.left && minRaceDepth(node.left,level + 1);
    //     node.right && minRaceDepth(node.right,level + 1);
    // }
    // minRaceDepth(root,1);
    // return min;

    // 2. 迭代BFS,寻找最小深度
    // let min = 2 ** 32 - 1;
    // let level = 1;
    // let queue = [];
    // queue.push(root);
    // while(queue.length > 0) {
    //     let levelSize = queue.length;
    //     for (let i = 0; i < levelSize; i ++) {
    //         let node = queue.shift();
    //         // 叶子节点
    //         if (!node.left && !node.right) {
    //             min = Math.min(min,level);
    //         }
    //         node.left && queue.push(node.left);
    //         node.right && queue.push(node.right);
    //     }
    //     level ++;
    // }
    // return min;

	// 3. 优雅的递归
    // 根节点
    if (!root.left && !root.right) return 1;
    
    // 处理左子树,右子树
    let leftDepth = minDepth(root.left);
    let rightDepth = minDepth(root.right);

    // 处理完后
    // 左右子树若有一个为空,则leftDepth或rightDepth就有一个为0
    return root.left === null || root.right === null ? 
        leftDepth + rightDepth + 1 : Math.min(leftDepth,rightDepth) + 1;
};

101.对称二叉树

  • 101.对称二叉树
    • 注意递归配合 逻辑运算符的使用 实现(无敌)
      • root.left.val === root.right.val
      • root.left.left.val === root.right.right.val
      • root.left.right.val === root.right.left.val
    var isSymmetric1 = function(root) {
        // 1. 迭代方式,减少空间复杂度,O(最后一层节点数)
        if (!root) return true;
    
        // 分别存储左右子树节点的栈
        let leftStack = [root.left];
        let rightStack = [root.right];
    
        // 会将null的节点也push进去
        do {
    
            let leftNode = leftStack.pop();
            let rightNode = rightStack.pop();
    
            if (leftNode === null && rightNode === null) continue;
            if (leftNode === null || rightNode === null || leftNode.val !== rightNode.val) return false;
    
            leftStack.push(leftNode.left);
            leftStack.push(leftNode.right);
    
            rightStack.push(rightNode.right);
            rightStack.push(rightNode.left);
    
        } while (leftStack.length > 0 && rightStack.length > 0);
        
        return true;
    };
    
    var isSymmetric2 = function (root) {
    	// 2. 递归实现,时间复杂度为O(n),需要递归n / 2次,空间复杂度为O(n),两侧为单链表,节点数为2n - 1
        function judgeTree(leftNode,rightNode) {
             if (leftNode === null && rightNode === null) return true;
             if (leftNode === null || rightNode === null || leftNode.val !== rightNode.val ) return false;
    
             // 这个递归配合 && 逻辑运算符是真的秀
             return judgeTree(leftNode.left,rightNode.right) && judgeTree(leftNode.right,rightNode.left);
         }
         return judgeTree(root.left,root.right);
    }
    

257.二叉树的所有路径

  • 257.二叉树的所有路径
    • 递归dfs + path参数记录路径
    var binaryTreePaths = function(root) {
    	if (!root) return [];
        if (!root.left && !root.right) return [String(root.val)];
    
    
        let res = [];
        function allPath(node,path) {
            if (!node.left && !node.right) {
                res.push(path);
                return null;
            }
            node.left && (node.left,path + "->" + node.left.val);
            node.right && (node.right,path + "->" + node.right.val);
        }   
        allPath(root,String(root.val));
        
        return res;
    }
    
    • 迭代bfs + 同步队列记录路径
    var binaryTreePaths = function(root) {
    	let queue_path = [];
        let queue_node = [];
        let res = [];
        queue_node.push(root);
        queue_path.push(String(root.val));
    
        // 同步队列记录路径
        while (queue_node.length > 0) {
    
            let node = queue_node.shift();
            let path = queue_path.shift();
            // 终止条件
            if (!node.left && !node.right) {
                res.push(path);
            } else {
                // 通过父节点来记录路径
                if (node.left) {
                    queue_node.push(node.left);
                    queue_path.push(path + "->" + node.left.val);
                }
                if (node.right) {
                    queue_node.push(node.right);
                    queue_path.push(path + "->" + node.right.val);
                }
            }
    
        }
        return res;
    }
    

404.左叶子之和

  • 404.左叶子之和
    var sumOfLeftLeaves = function(root) {
        if (!root) return 0; 
        let sum = 0;
        function dfs(node) {
            if (!node) return 0;
            if (node.left && !node.left.left && !node.left.right) {
                sum += node.left.val;
            }
            dfs(node.left);
            dfs(node.right);
        }
        dfs(root);
        return sum;
    };
    

513.找到左下角的值

  • 513.找到左下角的值
    • 转成最左边叶子节点 + 层级max的节点
      • 层序遍历最后一层的最左边节点值
      • dfs的层级max的最左边节点值
    var findBottomLeftValue = function(root) {
        // 1. 递归DFS
        if (!root) return 0;
        if (!root.left && !root.right) return root.val;
    
        // // 最底层 最左边 
        // let maxLevel = 0;
        // let maxLeftVal = 0;
        // function dfs(node,level) {
        //     if (!node.left && !node.right && maxLevel < level) {
        //         maxLevel = level;
        //         maxLeftVal = node.val;
        //     }
        //     node.left && dfs(node.left,level + 1);
        //     node.right && dfs(node.right,level + 1);
        // }
        // dfs(root,maxLevel);
        // return maxLeftVal;
    
        // 2. 迭代BFS
        let queue_node = [];
        let level = 0;
        let maxLevel = 0;
        let maxLeftVal = 0;
        queue_node.push(root);
    
        while (queue_node.length > 0) {
            let levelSize = queue_node.length;
            for (let i = 0; i < levelSize; i ++) {
                let node = queue_node.shift();
    
                if (!node.left && !node.right && level > maxLevel) {
                    maxLeftVal = node.val;
                    maxLevel = level;
                } else {
                    node.left && queue_node.push(node.left);
                    node.right && queue_node.push(node.right);
                }
            }
            level ++;
        }
    
        return maxLeftVal;
    };
    

112.路径总和

  • 112.路径总和
    var hasPathSum = function(root, targetSum) {
        // 迭代BFS
        if (!root) return false;
        let queue_node = [];
        let sum_queue = [];
        queue_node.push(root);
        sum_queue.push(root.val);
    
        while (queue_node.length > 0) {
            let node = queue_node.shift();
            let sum = sum_queue.shift();
    
            // 叶节点
            if (!node.left && !node.right && sum === targetSum) {
                return true;
            } else {
                if (node.left) {
                    queue_node.push(node.left);
                    sum_queue.push(sum + node.left.val);
                }
                if (node.right) {
                    queue_node.push(node.right);
                    sum_queue.push(sum + node.right.val);
                }
            }
        }
        return false;
    }
    

总结

  • 凡是 求二叉树的属性:路径,路径和,深度,节点数,最左叶子节点,最右叶子节点,左叶子之和,右叶子之和,对称二叉树等,都是通过 遍历二叉树,并在 途中记录信息 从而 得到
  • 而遍历二叉树除了前,中,后序遍历外,还有层级遍历,而相应的BFS,DFS搜索算法也很常用(需要掌握它们的 递归,迭代 实现)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值