zoukankan      html  css  js  c++  java
  • 二叉树中和为某一值的路经

    输入一颗二叉树和一个整数,找到二叉树中节点值得和为输入整数的所有路经。从根节点开始到叶子结点为一路经。

    思路:二叉树中,首先遍历根节点的是前序遍历。因为要从根节点开始,所以首先考虑前序遍历。在这个遍历的过程中,会从根节点开始,由左至右依次遍历二叉树的每一条路经。遍历到叶子结点时检查路经中的节点之和是否达到所求的节点值。

    还是看代码最清晰:所以直接上代码吧

    //二叉树中 和为某一值的路经
    struct TreeNode
    {
    	int val;
    	struct TreeNode *left;
    	struct TreeNode *right;
    	TreeNode(int x) :val(x), left(NULL), right(NULL){}
    };
    void push_res(vector<vector<int>> &res, TreeNode* root, vector<int> &path, int cur, int num)
    {
    	cur += root->val;
    	path.push_back(root->val);
    	if (root->left == NULL && root->right == NULL &&cur == num)
    		res.push_back(path);
    	if (root->left)
    		push_res(res, root->left, path, cur, num);
    	if (root->right)
    		push_res(res, root->right, path, cur, num);
    	path.pop_back();
    }
    vector<vector<int> > FindPath(TreeNode* root, int expectNumber) {
    	vector<vector<int>> res;
    	if (root == NULL)
    		return res;
    	vector<int> path;
    	int cur = 0;
    	push_res(res, root, path, cur, expectNumber);
    	return res;
    }
    
  • 相关阅读:
    Codeforces Round #394 (Div. 2) A. Dasha and Stairs
    HDU 1410 PK武林盟主
    HDU 3362 Fix(状压dp)
    P678-vect2.cpp
    Qt5获取本机网络信息
    Qt5标准文件对话框类
    nRF52832无法加载协议栈文件
    Debug记录(1)
    大小端模式
    nRF52832的SAADC
  • 原文地址:https://www.cnblogs.com/weiyi-mgh/p/6656814.html
Copyright © 2011-2022 走看看