24.二叉樹和爲某一值的路徑

二叉樹和爲某一值的路徑

題目鏈接
題目描述
輸入一顆二叉樹的根節點和一個整數,打印出二叉樹中結點值的和爲輸入整數的所有路徑。路徑定義爲從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。(注意: 在返回值的list中,數組長度大的數組靠前)

題意中兩個注意點:

  1. 所有路徑
  2. 從樹根結點到葉結點的路徑,葉結點也就是終端結點。

DFS

所有路徑結合二叉樹我們想到了DFS,使用遞歸幫我們方便的解決問題。

我們按照前序遍歷的方式,從二叉樹的根結點開始

路徑定爲path,路徑集合定爲ans,目標值爲target

  • 在根結點不爲NULL的情況下,開始遞歸
  • 將根結點的值放入path
  • 同時滿足和爲target、左結點爲NULL、右結點爲NULL三個條件則滿足題意的路徑,將path放入ans中
  • 和小於等於target時且左結點不爲NULL,遞歸左結點
  • 和小於等於target時且右結點不爲NULL,遞歸右結點
  • 將根結點的值從path中移除(這一步非常重要,保證DFS過程中狀態不影響其他狀態。)
  • 返回ans
/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    vector<vector<int> > ans;
    vector<int> path;
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        if (root == NULL)
        {
            return ans;
        }
        path.push_back(root->val);
        if (root->left == NULL && root->right == NULL && expectNumber == root->val)
        {
            ans.push_back(path);
        }
        if (root->left != NULL && root->val <= expectNumber)
        {
            FindPath(root->left, expectNumber-root->val);
        }
        if (root->right != NULL && root->val <= expectNumber)
        {
            FindPath(root->right, expectNumber-root->val);
        }
        vector<int>::iterator end = path.end();
        path.erase(--end);
        return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章