【Leetcode】105. Construct Binary Tree from Preorder and Inorder Traversal

题目地址:105. Construct Binary Tree from Preorder and Inorder Traversal
题意:根据前跟和中跟建立二叉树。.

递归方法:

class Solution {
public:
    TreeNode* buildTree(vector& preorder, vector& inorder) {
       return myBuildTree(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
    }
    TreeNode* myBuildTree(vector& preorder, int pLeft, int pRight, vector& inorder, int iLeft, int iRight) {
        if(pLeft>pRight||iLeft>iRight)return NULL;
         TreeNode* cur =new TreeNode(preorder[pLeft]);
        int i=0;
        for(i=iLeft;i<=iRight;i++){
            if(inorder[i]==preorder[pLeft])break;
        }
        cur->left = myBuildTree(preorder,pLeft+1,pLeft+i-iLeft,inorder,iLeft,i-1);
        cur->right= myBuildTree(preorder,pLeft+i-iLeft+1,pRight,inorder,i+1,iRight);
        return cur;
    }
};

非递归方法:

class Solution {
public:
    TreeNode* buildTree(vector& preorder, vector& inorder) {
        if(preorder.size()==0||inorder.size()==0) return NULL;
        stack st;
        TreeNode *cur =new TreeNode(preorder[0]);
        TreeNode *root = cur;
        for(int i=1,j=0;ival){
                cur->left = new TreeNode(preorder[i]);
                st.push(*cur);
                cur= cur->left;
            }else{
                j++;
                while(!st.empty()&&st.top().val==inorder[j]){
                    *cur =st.top() ;
                    st.pop();
                    j++;
                }
                cur->right = new TreeNode(preorder[i]);
                cur= cur->right;
            }
        }
        return root;
      
    }
  
};

你可能感兴趣的:(LEETCODE)