DFS-常规/热身

作者: zhouycoriginal | 来源:发表于2020-01-18 21:53 被阅读0次

DFS一般的流程是这样的:从一个点出发,遍历其中一个邻居节点w, 然后接着遍历w的一个邻居节点,当遍历到最后一个节点之后,回退回上一个已经被遍历过的节点,接着遍历这个节点的未被遍历的节点,依次循环,直到遍历完所有的点为止。

Maximum Depth of N-ary Tree

Given a n-ary tree, find its maximum depth.The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).


image.png
image.png
image.png
image.png

比较常规,用递归实现DFS的思路

class Solution {
public:
    int maxDepth(Node* root) {
        if(!root)
            return 0;
        int max_depth = 1;
        DFS(root,1,max_depth);
        return max_depth;
    }

    void DFS(Node *node, int depth, int &max_depth){
        if(!node) return;
        if((node->children).empty())
            max_depth = max(depth,max_depth);

        for(auto tmp_node:node->children)
            DFS(tmp_node,depth+1,max_depth);
    }
};

Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],return its depth = 3.


image.png
class Solution {
public:
    int maxDepth(TreeNode* root) {
        int max_depth = 0;
        DFS(root,1,max_depth);
        return max_depth;
    }

    void DFS(TreeNode *root, int depth, int &max_depth){
        if(!root) return;
        if(!root->left || root->right)
            max_depth = max(depth,max_depth);

        DFS(root->left,depth+1,max_depth);
        DFS(root->right,depth+1,max_depth);
    }
};

Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.


image.png

相关文章

  • DFS-常规/热身

    DFS一般的流程是这样的:从一个点出发,遍历其中一个邻居节点w, 然后接着遍历w的一个邻居节点,当遍历到最后一个节...

  • 2019-07-25三级跳反向摆臂示范课动图(电脑修改动图)

    具体过程: 一、准备部分: 1、 课堂常规 2、热身:学生交叉跑,后退跑 3、动态热身:(1)反向背部伸展 (2)...

  • DFS-数组

    题目原意: 小哼去解救小哈,地图为矩阵,上面有许多障碍物。求解救小哈的最短路径。 代码:

  • DFS-栈

    递归需要消耗额外的资源,这些资源是:1.递归由于是函数调用自身,而函数调用是有时间和空间的消耗的:每一次函数调用,...

  • dfs-岛屿面积

    LC-695这个做的比较快,一遍AC,之前在百练上做过一道一模一样的用dfs递归就可以 问题来了:思考 如何用栈实...

  • DFS-矩阵类

    这类问题一般给一个矩阵,要求矩阵内满足条件的一些元素。这类问题的一般做法是:先遍历整个矩阵,并找到要DFS的位置/...

  • 西湾例跑、去外甥家~2019年9月13日

    凌晨6:15分左右到达西湾公园参加例跑,常规流程:热身-合影-跑步-拉伸-吃早餐;下午去外甥家过节

  • 正确热身及训练(3000米)

    常规热身: 1.全身性伸展:重点拉伸大腿后侧以及小腿肌肉 (预防肌肉拉伤) 2.提高心肺:运用低强度原地练习,提高...

  • 初中物理电路 电流 电压易错精讲

    初中物理电路 电流 电压 易错精讲 有人说:初一是季前赛(热身),初二是常规赛(积累),初三是季后赛(冲刺) 有人...

  • 空中热身脊柱热身

    增加脊柱灵活性 拉长整个身体的侧向肌肉线条 括展胸腔,让肩关节更灵活 侧向伸展 回正 拱腰拱背抬头直立上身

网友评论

    本文标题:DFS-常规/热身

    本文链接:https://www.haomeiwen.com/subject/sljlzctx.html