zoukankan      html  css  js  c++  java
  • 前序遍历和中序遍历树构造二叉树

    • public class TreeNode {

    • public int val;
      
    • public TreeNode left, right;
      
    • public TreeNode(int val) {
      
    •     this.val = val;
      
    •     this.left = this.right = null;
      
    • }
      
    • }
      /
      public class Solution {
      /
      *
      *@param preorder : A list of integers that preorder traversal of a tree
      *@param inorder : A list of integers that inorder traversal of a tree
      *@return : Root of a tree
      /
      public TreeNode buildTree(int[] preorder, int[] inorder) {
      // write your code here
      vector pre_l,pre_r,in_l,in_r;//定义这四个变量来存储左右子树的前序和中序序列
      TreeNode
      root=NULL;
      int i=0;
      int index=0;
      if(!preorder.empty()||!inorder.empty())//如果序列中不为空,继续构建
      {
      root=new TreeNode(preorder[0]);

       for(i=0;i<inorder.size();i++)
       {
           if(preorder[0]==inorder[i])
           {
               index=i;//找出分割中序序列的分割点,左边为左子树的,右边为有子树的
             break;
           }
      
       }
       for(i=0;i<index;i++)//重新找出前面部分前中序列
       {
           pre_l.push_back(preorder[i+1]);
           in_l.push_back(inorder[i]);
       }
       for(i=index+1;i<inorder.size();i++)//找出后面部分的前中序列
       {
           pre_r.push_back(preorder[i]);
           in_r.push_back(inorder[i]);
       }
       //依次构建分割的部分,缩小区间,直至构建完
       root->left=buildTree(pre_l,in_l);
       root->right=buildTree(pre_r,in_r);
       }
       return root;
      

      }
      };

  • 相关阅读:
    为什么非全站升级HTTPS不可?
    使用JSON实现分页
    Git常用命令
    chrome浏览器tab页内存占用变大,网站变慢为哪般?
    我们前端跟后端是怎么合作的
    关于响应式布局
    AngularJS(1)
    关于php语言的使用!
    你必须收藏的Github技巧
    CSS3 动画
  • 原文地址:https://www.cnblogs.com/yiwenhao/p/7407561.html
Copyright © 2011-2022 走看看