zoukankan      html  css  js  c++  java
  • 剑指offer04-重建二叉树

    输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

    思路:前序遍历,第一个节点为二叉树root;中序遍历,左中右,root左边为左子树元素,右边为右子树元素;

    根据前序辨认出中间节点,再根据中序遍历和中间节点划分左子树和右子树;递归;

    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
            TreeNode*root=construct(pre,0,pre.size()-1,vin,0,vin.size()-1);
            return root;
        }
        TreeNode* construct(vector<int>pre,int pre_left,int pre_right,vector<int>vin,int vin_left,int vin_right)
        {
            TreeNode*head=new TreeNode(pre[pre_left]);
            for(int i=vin_left;i<=vin_right;i++)
            {
                if(vin[i]==pre[pre_left])
                {
                    if((i-vin_left)!=0)
                    head->left=construct(pre,pre_left+1,pre_left+i-vin_left,vin,vin_left,i-1);
                    if((vin_right-i)!=0)
                    head->right=construct(pre,pre_left+i-vin_left+1,pre_right,vin,i+1,vin_right);
                    
                }
                
            }
            return head;
        }

  • 相关阅读:
    项目知识
    设计师如何为 Android 应用标注尺寸
    Android开发注意事项
    线程的同步和异步
    复习:IPC机制
    简单的Mvp设计
    泛型
    RxBus的使用
    LinearLayout遇到的问题——利用LinearLayout做横向滑动冲突
    Google搜索技巧、使用Google的其它专业搜索
  • 原文地址:https://www.cnblogs.com/trouble-easy/p/12957923.html
Copyright © 2011-2022 走看看