劍指offer:打印二叉樹中和爲K的所有路徑: 二叉樹中和爲某一值的路徑

題目:

輸入一顆二叉樹的根節點和一個整數,打印出二叉樹中結點值的和爲輸入整數的所有路徑。路徑定義爲從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。

題目解析已經寫到代碼中啦!

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
// 要求返回所有路徑,路徑是指從根節點到葉子節點。
// 從根節點開始遍歷,如果根節點爲空則返回空,
// 若加上當前節點的值已經等於期望節點並且該節點爲葉子節點,則需要將該路徑加入總路徑統計中
// 否則,遍歷左子樹,左子樹遍歷完緊接着遍歷右子樹。可以從根節點開始遍歷,,
// 當改節點的左右子樹都已經遍歷完說明含有該節點的所有可能路徑都已經遍歷完
class Solution {
public:
    // 加上當前節點的值,判斷當前和是否等於期望值。如果相等且當前節點爲葉子節點則將路徑加入到總路徑統計中
    // 如果不是葉子節點則遍歷左右子樹,左右子樹都遍歷完則說明以該節點爲路徑節點的都已經遍歷完,返回到上一個節點。
    void FindPath(TreeNode* root,
                  vector<vector<int>> &paths,
                  vector<int>&path,
                  int currentSum,
                  int expectNumber) {
       currentSum +=root->val; //加上當前值
       path.push_back(root->val); //將當前節點壓入路徑
       bool isLeaf = (root->left== nullptr && root->right == nullptr);
       if(currentSum == expectNumber && isLeaf){ //是葉子節點並且和期望值相等,則加入到總路徑
           paths.push_back(path);
       }
       if(root->left !=nullptr)
           FindPath(root->left, paths,path, currentSum, expectNumber);
       if(root->right!=nullptr)
           FindPath(root->right, paths, path, currentSum, expectNumber);
        path.pop_back();
    }
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
          vector<vector<int>> paths;
          if(root == nullptr) return paths; //爲空直接返回paths
          vector<int>path; //定義一個路徑,currentSum - 0;
          FindPath(root, paths,path, 0, expectNumber);
          return paths;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章