1. 程式人生 > >Java, c++ 中序和前序 或 中序和後序構建二叉樹

Java, c++ 中序和前序 或 中序和後序構建二叉樹

利用遞迴,構建二叉樹的時候主要就是要搞清楚,前序和中序,後序與中序的關係,然後要遞迴地往下構建,先建當前節點的左孩子,再右孩子,然後我利用另外一種序列遍歷來驗證 構建的二叉樹是否正確。

#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 35;
int in[maxn];
int pre[maxn];
struct node {
    int data;
    node *lchild;
    node *rchild;
};


//inOrder和preOrder建立 樹
/* inOrder: 12 11 20 17 1 15 8 5 preOrder: 1 11 12 17 20 5 8 15 */ // or // //use the inOrder and preOrder create the binary tree node *Create(int preL, int preR, int inL,int inR) { if ( preL > preR ) return NULL; node *root = new node(); root->data = pre[preL]; int index; for
( index = inL; index <= inR; index++ ) { if ( in[index] == pre[preL] )break; } int numLeft = index - inL; root->lchild = Create(preL+1, preL+numLeft, inL, index-1); root->rchild = Create(preL+numLeft+1, preR, index+1, inR); return root; } void PostOrderTraversal(node *root) { if
( root != NULL ) { PostOrderTraversal(root->lchild); PostOrderTraversal(root->rchild); cout << root->data << " "; } } int main() { int n; cin >> n; for ( int i = 0 ; i < n; i++ ) { cin >> in[i]; } for ( int i = 0; i < n; i++ ) { cin >> pre[i]; } node *root; root = Create(0,n-1,0,n-1); PostOrderTraversal(root); return 0; } #include <iostream> #include <cstdio> using namespace std; const int maxn = 35; int in[maxn]; int post[maxn]; struct node { int data; node *lchild; node *rchild; }; //inOrder和postOrder 建立 樹 /* inOrder:12 11 20 17 1 15 8 5 postOrder:12 20 17 11 15 8 5 1 */ // use the inOrder and postOrder create the binary tree // node *Create(int postL, int postR, int inL, int inR) { if ( postL > postR ) return NULL; node *root = new node(); root->data = post[postR]; int index; for ( index = inL; index <= inR; index++ ) { if ( in[index] == post[postR] )break; } int numLeft = index - inL; root->lchild = Create(postL, postL+numLeft-1, inL, index-1); root->rchild = Create(postL+numLeft, postR-1, index+1, inR); return root; } void PreOrderTraversal(node *root) { if ( root != NULL ) { cout << root->data << " "; PreOrderTraversal(root->lchild); PreOrderTraversal(root->rchild); } } int main() { int n; cin >> n; for ( int i = 0 ; i < n; i++ ) { cin >> in[i]; } for ( int i = 0; i < n; i++ ) { cin >> post[i]; } node *root; root = Create(0,n-1,0,n-1); PreOrderTraversal(root); return 0; }

Java 先序和中序為例:

public class Solution {
   public static TreeNode reConstructBinaryTree(int [] pre,int [] in) {
       int in_size = in.length;
       if (in_size == 0) return null;
       int val = pre[0];
       TreeNode treeNode = new TreeNode(val);
       int i;
       for (i = 0; i < in_size; i++) {
           if (in[i] == val) break;
       }
       int[] pre_left = new int[i];
       int[] in_left = new int[i];
       int[] pre_right = new int[in_size-i-1];
       int[] in_right = new int[in_size-i-1];
       //left tree
       if (i > 0) {
           for (int j = 0; j < i; j++) {
               pre_left[j] = pre[j+1];
               in_left[j] = in[j];
           }
           treeNode.left = reConstructBinaryTree(pre_left, in_left);
       } else {
           treeNode.left = null;
       }
       //right tree
       if (in_size-i-1 > 0) {
           for (int j = i+1; j < in_size; j++) {
               pre_right[j-i-1] = pre[j];
               in_right[j-i-1] = in[j];
           }
           treeNode.right = reConstructBinaryTree(pre_right, in_right);
       } else {
           treeNode.right = null;
       }
       return treeNode;
   }
    public static class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode(int x) { val = x; }
    }
    public static void PostTraversal(TreeNode treeNode) {
        if (treeNode != null){
            PostTraversal(treeNode.left);
            PostTraversal(treeNode.right);
            System.out.print(treeNode.val+" ");
        }
    }
    static int[] pre = {1, 2, 4, 7, 3, 5, 6, 8};
    static int[] in = {4, 7, 2, 1, 5, 3, 8, 6};
    public static TreeNode BuildTree(int PreL, int PreR, int inL, int inR) {
        if (PreL > PreR) return null;
        int val = pre[PreL];
        TreeNode treeNode = new TreeNode(val);
        int i;
        for (i = inL; i <= inR; i++) {
            if (in[i] == val) break;
        }
        int numleft =  i - inL;
        treeNode.left = BuildTree(PreL+1, PreL+numleft, inL, i-1);
        treeNode.right = BuildTree(PreL+numleft+1, PreR, i+1, inR);
        return treeNode;
    }

    public static void main(String[] args) {

        TreeNode treeNode1 = reConstructBinaryTree(pre, in);
        PostTraversal(treeNode1);
        int len = pre.length;
        System.out.println();
        TreeNode treeNode2 = BuildTree(0, len-1, 0, len-1);
        PostTraversal(treeNode2);
    }
}

相關推薦

Java, c++ 構建

利用遞迴,構建二叉樹的時候主要就是要搞清楚,前序和中序,後序與中序的關係,然後要遞迴地往下構建,先建當前節點的左孩子,再右孩子,然後我利用另外一種序列遍歷來驗證 構建的二叉樹是否正確。 #include <iostream> #include

根據遍歷遍歷構建c語言完整程式碼

//重建二叉樹:輸入某二叉樹的前序和中序遍歷,重建出該二叉樹 #include<stdio.h> #include<malloc.h> typedef struct binarytreenode { int value; struct

已知序列,構建並求序列,java實現。

已知二叉樹的前序和中序序列,或者已知二叉樹的後序和中序序列,是能夠唯一確定一棵二叉樹的。但是如果僅知道二叉樹的前序和後序序列,一般是不能唯一確定一棵二叉樹的,但是可以分析有多少種可能的二叉樹,這個沒有具體研究,只知道節點少的情況還能湊合分析出來,但是節點多的情況下可能性太多

遍歷遍歷構建

[] for 中序 break pan n) turn star 前序遍歷 public Node reConstructBinaryTree(int[] pre,int[] in){ if(pre==null || in ==null){

根據構建

進行遞迴 # -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right =

Leetcode 已知)遍歷遍歷構建

我們知道,中序遍歷是左子樹->根節點->右子樹。因此我們可以通過中序遍歷可以確定左右子樹的元素個數。 而通過前序(後序)遍歷,我們可以確定根節點的位置,然後通過尋找根節點在中序遍歷的位置,可以確定左右子樹。 然後遞迴遞迴左右子樹實現構建二叉樹。 前序和中序:

系列——根據構建

1、根據前序和中序構建二叉樹 思路:在二叉樹的前序遍歷序列中,第一個數字總是樹的根節點的值。但在中序遍歷序列中,根節點的值在序列的中間,左子樹的節點的值位於根節點的值得左邊,而右子樹的節點的值位於根節

面試題6:根據序列構建(Leetcode-106)

題目:輸入二叉樹的前序遍歷和中序遍歷序列,重構其二叉樹,假設輸入的數字都是不重複的。 例如前序序列是 {1,2,4,7,3,5,6,8},中序序列是{4,7,2,1,5,3,8,6}。 分析如下圖所示: 演算法步驟: 1. 前序序列的第一個元素即根節

資料結構與演算法簡記:通過構建

上次記錄了廣義表生成二叉樹的過程,我們也可以通過前序和中序,或者中序和後序,來確定和構建一棵唯一的二叉樹。 還是同樣的圖,它的前序,中序,後序遍歷序列分別是: pre: ABCDEF in: CBDAEF post: CDBFEA 以下是通過前序和中

構建

[] pri light index blog log highlight tree cnblogs public Node PreMidToTree(int[] pre,int[] mid) { if (pre == null || mi

遍歷遍歷/遍歷構建

1:問題 給定二叉樹的2個遍歷序列(如先序+中序,先序+後序,中序+後序等),是否能夠根據這2個遍歷序列唯一確定二叉樹? struct BinaryTreeNode { int m_nValue; BinaryTreeNode* m_pLeft; BinaryTree

的學習——(遞迴構建、遞迴非遞迴遍歷、根據序列、序列構建

前言 最近兩個星期一直都在斷斷續續的學習二叉樹的資料結構,昨晚突然有點融匯貫通的感覺,這裡記錄一下吧 題目要求 給定前序序列,abc##de#g##f###,構建二叉樹,並且用遞迴和非遞迴兩種方法去做前序,中序和後序遍歷 二叉樹的資料結構 #define STACKSI

給定遍歷構建

class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class

根據先構建

#include<bits/stdc++.h> using namespace std; typedef struct node { char data; struct no

c++ 先構建

二叉樹首先要解決構建問題,才能考慮後續的遍歷,這裡貼出通過先序構建二叉樹,同時包含四種二叉樹的遍歷方法(先序,中序,後序,逐層) 第一、定義BinaryTreeNode 類 1 #include <iostream> 2 #include <string>

【資料結構週週練】014 利用棧非遞迴演算法求鏈式儲存的是否為完全

一、前言 首先,明天是個很重要的節日,以後我也會過這個節日,在這裡,提前祝所有程式猿們,猿猴節快樂,哦不,是1024程式設計師節快樂。 今天要給大家分享的演算法是判斷二叉樹是否為完全二叉樹,相信大家對完全二叉樹的概念並不陌生,如果是順序儲存就會很方便,那鏈式儲存怎麼判斷呢,我的做法是:若

C++實現利用(生成)以及(的鏡像)

lse pub 非遞歸 ace 方法 [] reorder spa push #include<iostream> #include<string.h> #include<stack> using namespace std; type

的遍歷的遞迴非遞迴程式碼-C語言

#include <stdio.h> #include<stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input l

c++的遞迴非遞迴的遍歷以及層遍歷

二叉樹的遞迴版的前序,中序和後序遍歷很簡單也很容易理解,這裡就放一個前序遍歷的例子 //前序遍歷遞迴演算法,遞迴演算法都大同小異,這裡就不一一列舉了 void binaryTree::pro_order(NodeStack::Node *t) { NodeStack::Node *h = t;

輸入某遍歷遍歷的結果,請重建出該(java實現並測試)

假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。 package ssp; class TreeNode { int val; TreeNod