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;
    }
};

  

原文地址:https://www.cnblogs.com/xinsheng/p/3439524.html