根據二叉樹的前序遍歷和中序遍歷構造二叉樹

2021-08-08 03:14:46 字數 616 閱讀 3242

題:給出某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列pre:和中序遍歷序列in:,則重建二叉樹並返回。

思路:令pi=pre[0],由二叉樹的前序遍歷特性可知pi為二叉樹的根節點root,遍歷in,得到in[j]==pi的下標j,由二叉樹的前序遍歷和中序遍歷的特性可知,pre陣列中從pre[1]到pre[i]為pre[0]的左子樹的前序遍歷陣列,從pre[i+1]到pre陣列最後為pre[0]的右子樹的前序遍歷;in陣列中從in[0]到in[i-1]為pre[0]的左子樹的中序遍歷,從in[i+1]到in陣列最後為pre[0]的右子樹的中序遍歷。一直遞迴,即可還原出原二叉樹。

**:

public treenode reconstructbinarytree(int  pre,int  in) 

}return resultnode;

}

treenode類:

class treenode 

}

根據前序遍歷和中序遍歷重建二叉樹

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。class treenode public class s2 public treenode reconstruct int pre...

根據前序遍歷和中序遍歷重建二叉樹

package com.study 根據二叉樹的前序遍歷和中序遍歷結果重建二叉樹 並輸出其頭節點。假設前序遍歷和中序遍歷結果中沒有重複數字 前序遍歷序列 中序遍歷序列 class treenode public class suanfa4 private static int arr2 public...

根據前序遍歷和中序遍歷樹構造二叉樹

根據前序遍歷和中序遍歷樹構造二叉樹.樣例給出中序遍歷 1,2,3 和前序遍歷 2,1,3 返回如下的樹 2 1 3 假設樹中不存在相同數值的節點 definition of treenode class treenode class solution treenode helper vector p...