zoukankan      html  css  js  c++  java
  • Leetcode: mimimum depth of tree, path sum, path sum II

    思路:

    简单搜索

    总结:

    dfs 框架

    1. 需要打印路径. 在 dfs 函数中假如 vector 变量, 不用 & 修饰的话就不需要 undo

    2. 不需要打印路径, 可设置全局变量 ans, 在 dfs 函数中对 ans 判定, 判定的位置尽可能的多

    3. 对 tree 遍历, 有两种办法, 第一种是 if(root == NULL) 第二种是 if(root->left == NULL), 我一般用第二种, 效率比较高, 但是在第二种 return 1, 第一种 return 0

    4. Leetcode 给出的测试用例经常会有空的输入, 要注意

    5. path sum 中树节点的 val 可以是负数, 使得剪枝变得比较困难. 这个地方 wa 过

    6. path sum II 题目没要求去重, 去重的话可能比较复杂, 我暂时没想到好办法

    7. vector.clear() 可以彻底清空 vector, 不需要  for 循环

    代码:

    minimum depth of tree

     const int INF = 1E9;
    class Solution {
    public:
        int minDepth(TreeNode *root) {
    		if(root == NULL)
    			return 0;
    
    		if(root->left == NULL && root->right == NULL) 
    			return 1;
    		
    		int left = INF, right = INF;
    		if(root->left) {
    			left = 1 + minDepth(root->left);			
    		}
    		if(root->right)
    			right = 1 + minDepth(root->right);
    		
    		return min(left, right);
        }
    };
    

      

    path sum

    class Solution {
    public:
    	int SUM;
    	bool ans;
    	
    	void dfs(TreeNode *root, const int &curSum) {
    		if(ans)
    			return;
    		
    		if(curSum + root->val == SUM) {
    			if(root->left == NULL && root->right == NULL) {
    				ans = true;
    				return;
    			}
    		}
    		if(root->left != NULL && !ans) {
    			dfs(root->left, curSum+root->val);
    		}
    		if(root->right != NULL && !ans) {
    			dfs(root->right, curSum+root->val);
    		}
    		
    	}
        bool hasPathSum(TreeNode *root, int sum) {
          SUM = sum;
    	  ans = false;
    	  if(root == NULL)
    		  return false;
    	  else
    		dfs(root, 0);
    	  return ans;
        }
    };
    

      

    path sum II

    class Solution {
    public:
    	int SUM;
    	vector<vector<int> > result;
    
    	void dfs(TreeNode *root, const int &curSum, vector<int> party) {
    		party.push_back(root->val);
    		if(curSum + root->val == SUM) {
    			if(root->left == NULL && root->right == NULL) {
    				result.push_back(party);
    				return;
    			}
    		}
    		if(root->left != NULL ) {
    			dfs(root->left, curSum+root->val, party);
    		}
    		if(root->right != NULL ) {
    			dfs(root->right, curSum+root->val, party);
    		}
    		
    	}
        vector<vector<int> > pathSum(TreeNode *root, int sum) {
          SUM = sum;
    	  result.clear();
    	  if(root != NULL) {
    		  vector<int> temp;
    		  dfs(root, 0, temp);
    	  }
    	  return result;
        }
    };
    

      

  • 相关阅读:
    如何监控IT正常运行时间?
    系统扩展正在取代macOS内核扩展,这会对您有何影响?
    IT管理员需要的10大网络工具
    自动化管理员工生命周期,集成Ultipro
    OpManager MSP:ManageEngine的新型MSP重点网络监控解决方案
    vue中axios的使用
    vue中axios的介绍
    移动端适配--关于根元素font-size和rem
    JavaScript---数组去重
    array数组的方法
  • 原文地址:https://www.cnblogs.com/xinsheng/p/3439524.html
Copyright © 2011-2022 走看看