zoukankan      html  css  js  c++  java
  • Solve Tree Problems Recursively

    "Top-down" Solution

    Here is the pseudocode for the recursion function maximum_depth(root, depth):

    1. return if root is null
    2. if root is a leaf node:
    3.      answer = max(answer, depth)         // update the answer if needed
    4. maximum_depth(root.left, depth + 1)      // call the function recursively for left child
    5. maximum_depth(root.right, depth + 1)     // call the function recursively for right child
    

      

     code:
    int answer;		       // don't forget to initialize answer before call maximum_depth
    void maximum_depth(TreeNode* root, int depth) {
        if (!root) {
            return;
        }
        if (!root->left && !root->right) {
            answer = max(answer, depth);
        }
        maximum_depth(root->left, depth + 1);
        maximum_depth(root->right, depth + 1);
    }
    

      

    "Bottom-up" Solution

    1. return 0 if root is null                 // return 0 for null node
    2. left_depth = maximum_depth(root.left)
    3. right_depth = maximum_depth(root.right)
    4. return max(left_depth, right_depth) + 1  // return depth of the subtree rooted at root
    

      

    code:

    int maximum_depth(TreeNode* root) {
    	if (!root) {
    		return 0;                                 // return 0 for null node
    	}
    	int left_depth = maximum_depth(root->left);	
    	int right_depth = maximum_depth(root->right);
    	return max(left_depth, right_depth) + 1;	  // return depth of the subtree rooted at root
    }
    

      

    Conclusion.

    It is not easy to understand recursion and find out a recursion solution for the problem.

    When you meet a tree problem, ask yourself two questions: can you determine some parameters to help the node know the answer of itself? Can you use these parameters and the value of the node itself to determine what should be the parameters parsing to its children? If the answers are both yes, try to solve this problem using a "top-down" recursion solution.

    Or you can think the problem in this way: for a node in a tree, if you know the answer of its children, can you calculate the answer of the node? If the answer is yes, solving the problem recursively from bottom up might be a good way.

    In the following sections, we provide several classic problems for you to help you understand tree structure and recursion better.

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    天才AI少年范浩强坚信“弄斧要到班门”
    向Excel说再见,神级编辑器统一表格与Python
    疯狂脑机接口计划:马斯克的 “读心术”
    Jenkins 学习资料
    VMware: windows8 与 虚拟机ubuntu 14.04 共享文件夹
    [转载]一个老软件测试工程师的日志
    python 解析 配置文件
    借助github搭建自己的博客
    [转载]你需要知道的 16 个 Linux 服务器监控命令
    [转载]Linux服务器性能评估与优化
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9996766.html
Copyright © 2011-2022 走看看