zoukankan      html  css  js  c++  java
  • 二叉树-专题

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

    /**
    * Definition for a binary tree node.
    * struct TreeNode {
    * int val;
    * TreeNode *left;
    * TreeNode *right;
    * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    * };
    */

    class Solution {
    public:
    vector<int> postorderTraversal(TreeNode* root) {
    map<TreeNode*,bool> mymap;
    vector<int> ret;
    stack<TreeNode*> mystac;
    TreeNode* p=root;
    while(p||!mystac.empty())
    {
    while(p)
    {

    mystac.push(p);
    mymap[p]=false;
    p=p->left;

    }

    if(!mystac.empty())
    {
    TreeNode* tmp=mystac.top();
    mystac.pop();
    if(mymap[tmp]==false)
    {
    mymap[tmp]=true;
    mystac.push(tmp);
    p=tmp->right;
    }
    else
    {
    ret.push_back(tmp->val);
    p=NULL;
    }
    }
    }

    return ret;

    }
    };

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

    vector<int> preorderTraversal(TreeNode *root) {
            // write your code here
            vector<int> ret;
            stack<TreeNode*> 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<vector<int>>& ret,vector<int> 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<vector<int> > FindPath(TreeNode* root,int expectNumber) {
            vector<vector<int>> ret;
            vector<int> tmp;
            dfs(root,expectNumber,0,ret,tmp);
            return ret;
        }
    };
    

      

  • 相关阅读:
    ubuntu安装KVM
    从磁盘上卸载虚拟机安装的系统,彻底删除虚拟机
    VIM退出命令
    ubuntu修改IP地址和网关的方法
    linux 创建连接命令 ln -s 软链接
    OVF? OVA? VMDK? – File Formats and Tools for Virtualization
    How to: Launch the Debugger Automatically
    winform listview默认第一项光标选中
    基于TCP通信的客户端断线重连
    客户端程序传送图片到服务器
  • 原文地址:https://www.cnblogs.com/wuxiangli/p/7295576.html
Copyright © 2011-2022 走看看