zoukankan      html  css  js  c++  java
  • [NewCode 6] 重建二叉树

    题目描述

    输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并输出它的后序遍历序列。(测试用例中,"树"的输出形式类似于树的层次遍历,没有节点的用#来代替)

    image

    除了一些编译错误,一遍AC了,真是爽。由于树本身就是递归定义的,因此关于树的题目大部分都可以用递归来做。这道题是重建二叉树,怎么考虑递归呢?其实很简单,考虑根是谁?左孩子是谁?右孩子是谁?代码如下:

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
    	TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {
    		TreeNode *root;
            return reConstructBinaryTree_help(pre, in);
    	}
        
    private:
       TreeNode* reConstructBinaryTree_help(const vector<int> pre, const vector<int> in) {
           if (in.empty()) {
               return NULL;
           }
           TreeNode *root = new TreeNode(pre[0]);
           
           // 处理中序遍历的vector
           vector<int>::const_iterator itr = find(in.cbegin(), in.cend(), pre[0]);
           vector<int> leftIn(in.cbegin(), itr);
           vector<int> rightIn(itr + 1, in.cend());
           
           // 处理前序遍历的vector
           int leftPreSize = leftIn.size();
           vector<int> leftPre(pre.cbegin() + 1, pre.cbegin() + leftPreSize + 1);
           vector<int> rightPre(pre.cbegin() + leftPreSize + 1, pre.cend());
           
           // 递归
           root->left = reConstructBinaryTree_help(leftPre, leftIn);
           root->right = reConstructBinaryTree_help(rightPre, rightIn);
           
           return root;
           
       }
    };
  • 相关阅读:
    修改Chrome设置伪装成手机M站
    使用Chrome浏览器自动将文件下载到指定路径
    操作HTML5存储对象
    在HTML5的画布元素上进行绘画操作
    测试HTML5语言实现的视频播放器
    封装操作表格的公用类
    测试过程中发生异常或断言失败时进行屏幕截图
    浏览器中新开标签页(Tab)
    高亮显示正在操作的页面元素
    精确比较页面截图图片
  • 原文地址:https://www.cnblogs.com/jianxinzhou/p/4492828.html
Copyright © 2011-2022 走看看