二叉树-专题

题型一:非递归遍历二叉树后续

struct node
 {
    bool isfirst;
    int val;
    TreeNode* left,*right;
    node(int _val,bool _isfirst){
        val=_val;
        isfirst=_isfirst;
        this->left=this->right=NULL;
    }
 };

vector postorderTraversal(TreeNode *root) {
        // write your code here
        vector ret;
        stack sta;
        TreeNode* p=root;
        while(sta.size()>0||p)
        {
            while(p)
            {
                node n1(p->val,false);
                n1.left=p->left;
                n1.right=p->right;
                sta.push(n1);
                p=p->left;
            }
            if(sta.size()>0)
            {
                node tmp=sta.top();
                sta.pop();
                if(tmp.isfirst==false)
                {
                    tmp.isfirst=true;
                    sta.push(tmp);
                    p=tmp.right;
                }
                else
                {
                    ret.push_back(tmp.val);
                    p=NULL;
                }
            }
        }
        return ret;
    }

  题型二:非递归二叉序前序遍历(中序差不多,就不写了,自己去脑补去。。。。中序的逆序是直接先遍历右边再遍历左边,orz

vector preorderTraversal(TreeNode *root) {
        // write your code here
        vector ret;
        stack sta;
        TreeNode* p=root;
        while(sta.size()>0||p)
        {
            while(p)
            {
                sta.push(p);
                ret.push_back(p->val);
                p=p->left;
            }
            if(sta.size())
            {
                TreeNode* tmp=sta.top();
                sta.pop();
                p=tmp->right;
            }
        }
        return ret;
    }

  二叉树中和为某一值的路径:

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    void dfs(TreeNode* root,int e,int sum,vector>& ret,vector tmp)
    {

        if(root)
        {
            if(sum+root->val==e&&root->left==NULL&&root->right==NULL)
            {
                tmp.push_back(root->val);
                ret.push_back(tmp);
                return;
            }
            tmp.push_back(root->val);
            dfs(root->left,e,root->val+sum,ret,tmp);
            dfs(root->right,e,root->val+sum,ret,tmp);
        }

    }
    vector > FindPath(TreeNode* root,int expectNumber) {
        vector> ret;
        vector tmp;
        dfs(root,expectNumber,0,ret,tmp);
        return ret;
    }
};

  

转载于:https://www.cnblogs.com/wuxiangli/p/7295576.html

你可能感兴趣的:(二叉树-专题)