import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }
}

class TaskB {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int n=in.readInt();
        int[] arr1=new int[(1<<(n+1))], arr2=new int[(1<<(n+1))];
        for (int i=2; i<1<<(n+1); i++) arr1[i]=in.readInt()+arr1[i/2];
        int max= ArrayUtils.maxElement(arr1);
        for (int i=1<<n; i<1<<(n+1); i++) arr2[i]=max-arr1[i];
        for (int i=(1<<n)-1; i>=1; i--) {
            int min= MiscUtils.min(arr2[2 * i], arr2[2 * i + 1]);
            arr2[i]=min;
            arr2[2*i]-=min;
            arr2[2*i+1]-=min;
        }
        out.printLine(ArrayUtils.sumArray(arr2));
    }
}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private SpaceCharFilter filter;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    public int read() {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public boolean isSpaceChar(int c) {
        if (filter != null)
            return filter.isSpaceChar(c);
        return isWhitespace(c);
    }

    public static boolean isWhitespace(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public interface SpaceCharFilter {
        public boolean isSpaceChar(int ch);
    }
}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public void close() {
        writer.close();
    }

    public void printLine(long i) {
        writer.println(i);
    }

}

class ArrayUtils {

    public static long sumArray(int[] array) {
        long result = 0;
        for (int element : array)
            result += element;
        return result;
    }

    public static int maxElement(int[] array) {
        return maxElement(array, 0, array.length);
    }

    public static int maxElement(int[] array, int from, int to) {
        int result = Integer.MIN_VALUE;
        for (int i = from; i < to; i++)
            result = Math.max(result, array[i]);
        return result;
    }

}

class MiscUtils {

    public static<T extends Comparable<T>> T min(T first, T second) {
        if (first.compareTo(second) <= 0)
            return first;
        return second;
    }

}


import java.util.*;
public class TaskB {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan=new Scanner(System.in);
		int n=scan.nextInt();
		int amount=0;
		int step=1;
		for(int i=0;i<n;i++)
		{
			step*=2;
			amount+=step;

		}
		int[] a=new int[(amount+10)];

		for(int i=2;i<amount+2;i++)
		{
			a[i]=scan.nextInt();
		}

		int additional=0;
		int last=amount+1;
		while(step>1)
		{
			for(int i=last;i>last-step;i-=2)
			{
				if(a[i]<a[i-1])
				{
					additional+=a[i-1]-a[i];
					a[i/2]+=a[i-1];
				}
				else
				{
					additional+=a[i]-a[i-1];
					a[i/2]+=a[i];
				}

			}
			last-=step;
			step/=2;

		}
		System.out.println(additional);
	}

}


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class a {
    public static int sum=0;
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n=s.nextInt();
        int a[]=new int[(int)Math.pow(2,n+1)-1];
        for(int i=1;i<a.length;i++)
           a[i]=s.nextInt();
        int n1=(int)Math.pow(2,n)-2;
        f(a,n1,0);
        System.out.println(sum);
    }
    public static int f(int a[], int n,int c){
       // System.out.println(n+"  "+c+"  "+sum);
        if(c>n){
          return a[c];
        }
        else{

           a[c]+=Math.max(f(a,n,2*c+2),f(a,n,2*c+1));
            sum+=Math.abs(a[2*c+1]-a[2*c+2]);
           return a[c];
        }

    }
}


import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.InputMismatchException;

public class Main {
    static Main root;
    int node;
    int lights;
    Main left;
    Main right;
    int sum;
    public Main() {}
    public Main(int n, int lights) {
        this.node = n;
        left = null;
        right = null;
        this.lights = lights;
        sum = -1;
    }

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        new Main().start(in, out);
        out.close();
    }

    public void start(InputReader in, OutputWriter out) {
        int n = in.nextInt();
        int p = (int)Math.pow(2,(n+1));
        ArrayList<Main> graph = new ArrayList<Main>();
        graph.add(new Main(1,-1));
        int index;
        for(int i=2 ; i<p ; i+=2) {
            index = i/2;
            Main m = new Main(i,in.nextInt());
            graph.get(index-1).left = m;
            graph.add(m);
            m = new Main(i+1,in.nextInt());
            graph.get(index-1).right = m;
            graph.add(m);
        }
        root = graph.get(0);
        out.printLine(solve(graph.get(0),null));
    }

    public int solve(Main tree, Main parent) {
        int min = 0;
        if(tree.left != null) {
            min += solve(tree.left,tree); // min = 1, 1.tree.sum = 5
            if(tree.right != null) {
                min += solve(tree.right,tree); // min = 1, 2.tree.sum = 4
                //min += Math.abs((tree.lights+tree.sum) - parent.sum);
                if(parent != null) {

                        if(parent.sum == -1) {
                            parent.sum = tree.lights+tree.sum;
                        } else {
                            min += Math.abs(parent.sum - (tree.lights+tree.sum));
                        }

                } else {

                }
            }
        }
        else {
            //int min = Math.abs(tree.lights - parent.right.lights);
            if(parent != null) {
                if(parent.sum == -1) {
                    parent.sum = tree.lights;
                    //solve(parent.right,parent);
                } else {
                    min = Math.abs(tree.lights - parent.sum);
                    parent.sum = Math.max(tree.lights, parent.sum);
                }
            }
        }
        return min;
    }
}

class InputReader {
    private InputStream stream;
    private byte[] buffer = new byte[10000];
    private int cur;
    private int count;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    public static boolean isSpace(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public int read() {
        if (count == -1) {
            throw new InputMismatchException();
        }
        try {
            if (cur >= count) {
                cur = 0;
                count = stream.read(buffer);
                if (count <= 0)
                    return -1;
            }
        } catch (IOException e) {
            throw new InputMismatchException();
        }
        return buffer[cur++];
    }

    public int readSkipSpace() {
        int c;
        do {
            c = read();
        } while (isSpace(c));
        return c;
    }

    public int nextInt() {
        int sgn = 1;
        int c = readSkipSpace();
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9') {
                throw new InputMismatchException();
            }
            res = res * 10 + c - '0';
            c = read();
        } while (!isSpace(c));
        res *= sgn;
        return res;
    }

    public String next() {
        int c = readSkipSpace();
        StringBuilder sb = new StringBuilder();
        while (!isSpace(c)) {
            sb.append((char) c);
            c = read();
        }
        return sb.toString();
    }
}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public OutputWriter(Writer writer) {
        this.writer = new PrintWriter(writer);
    }

    public void print(Object... objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0) {
                writer.print(' ');
            }
            writer.print(objects[i]);
        }
    }

    public void printLine(Object... objects) {
        print(objects);
        writer.println();
    }

    public void close() {
        writer.close();
    }

}


import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.InputMismatchException;

public class Main {
    static Main root;
    int node;
    int lights;
    Main left;
    Main right;
    int sum;
    public Main() {}
    public Main(int n, int lights) {
        this.node = n;
        left = null;
        right = null;
        this.lights = lights;
        sum = -1;
    }

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        new Main().start(in, out);
        out.close();
    }

    public void start(InputReader in, OutputWriter out) {
        int n = in.nextInt();
        int p = (int)Math.pow(2,(n+1));
        ArrayList<Main> graph = new ArrayList<Main>();
        graph.add(new Main(1,-1));
        int index;
        for(int i=2 ; i<p ; i+=2) {
            index = i/2;
            Main m = new Main(i,in.nextInt());
            graph.get(index-1).left = m;
            graph.add(m);
            m = new Main(i+1,in.nextInt());
            graph.get(index-1).right = m;
            graph.add(m);
        }
        root = graph.get(0);
        out.printLine(solve(graph.get(0),null));
    }

    public int solve(Main tree, Main parent) {
        int min = 0;
        if(tree.left != null) {
            min += solve(tree.left,tree); // min = 1, 1.tree.sum = 5
            if(tree.right != null) {
                min += solve(tree.right,tree); // min = 1, 2.tree.sum = 4
                if(parent != null) {
                    if(parent.sum == -1) {
                        parent.sum = tree.lights+tree.sum;
                    } else {
                        min += Math.abs(parent.sum - (tree.lights+tree.sum));
                        parent.sum = Math.max(parent.sum, tree.lights+tree.sum);
                    }
                }
            }
        }
        else {
            //int min = Math.abs(tree.lights - parent.right.lights);
            if(parent != null) {
                if(parent.sum == -1) {
                    parent.sum = tree.lights;
                    //solve(parent.right,parent);
                } else {
                    min = Math.abs(tree.lights - parent.sum);
                    parent.sum = Math.max(tree.lights, parent.sum);
                }
            }
        }
        return min;
    }
}

class InputReader {
    private InputStream stream;
    private byte[] buffer = new byte[10000];
    private int cur;
    private int count;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    public static boolean isSpace(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public int read() {
        if (count == -1) {
            throw new InputMismatchException();
        }
        try {
            if (cur >= count) {
                cur = 0;
                count = stream.read(buffer);
                if (count <= 0)
                    return -1;
            }
        } catch (IOException e) {
            throw new InputMismatchException();
        }
        return buffer[cur++];
    }

    public int readSkipSpace() {
        int c;
        do {
            c = read();
        } while (isSpace(c));
        return c;
    }

    public int nextInt() {
        int sgn = 1;
        int c = readSkipSpace();
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9') {
                throw new InputMismatchException();
            }
            res = res * 10 + c - '0';
            c = read();
        } while (!isSpace(c));
        res *= sgn;
        return res;
    }

    public String next() {
        int c = readSkipSpace();
        StringBuilder sb = new StringBuilder();
        while (!isSpace(c)) {
            sb.append((char) c);
            c = read();
        }
        return sb.toString();
    }
}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public OutputWriter(Writer writer) {
        this.writer = new PrintWriter(writer);
    }

    public void print(Object... objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0) {
                writer.print(' ');
            }
            writer.print(objects[i]);
        }
    }

    public void printLine(Object... objects) {
        print(objects);
        writer.println();
    }

    public void close() {
        writer.close();
    }

}


import java.io.*;
import java.math.BigInteger;
import java.util.*;

public class Template implements Runnable {

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

    void init() throws FileNotFoundException {
        try {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        } catch (Exception e) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        }
    }

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            try {
                tok = new StringTokenizer(in.readLine(), " :");
            } catch (Exception e) {
                return null;
            }
        }
        return tok.nextToken();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    int[] readIntArray(int size) throws IOException {
        int[] res = new int[size];
        for (int i = 0; i < size; i++) {
            res[i] = readInt();
        }
        return res;
    }

    long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }

    <T> List<T>[] createGraphList(int size) {
        List<T>[] list = new List[size];
        for (int i = 0; i < size; i++) {
            list[i] = new ArrayList<>();
        }
        return list;
    }

    public static void main(String[] args) {
        new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start();
    }

    long timeBegin, timeEnd;

    void time() {
        timeEnd = System.currentTimeMillis();
        System.err.println("Time = " + (timeEnd - timeBegin));
    }

    long memoryTotal, memoryFree;

    void memory() {
        memoryFree = Runtime.getRuntime().freeMemory();
        System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10)
                + " KB");
    }

    public void run() {
        try {
            timeBegin = System.currentTimeMillis();
            memoryTotal = Runtime.getRuntime().freeMemory();
            init();
            solve();
            out.close();
            if (System.getProperty("ONLINE_JUDGE") == null) {
                time();
                memory();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    int p(int x) {
        return 1 << x;
    }

    int[] a;
    int n;
    long answer = 0;

    long solveFor(int x, int depth) {
        if (depth == n) return 0;
        int lv = 2 * x;
        int rv = 2 * x + 1;
        long left = solveFor(lv, depth + 1) + a[lv - 2];
        long right = solveFor(rv, depth + 1) + a[rv - 2];
        long min = Math.min(left, right);
        long max = Math.max(left, right);
        answer += max - min;
        return max;
    }

    void solve() throws IOException {
        n = readInt();
        a = readIntArray(p(n + 1) - 2);
        solveFor(1,0);
        out.println(answer);
    }

}


import java.beans.IntrospectionException;
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.lang.*;
import static java.lang.Math.*;
public class main implements Runnable {

    static ArrayList<Integer> adj[];

    static void Check2(int n) {
        adj = new ArrayList[n + 1];
        for (int i = 0; i <= n; i++) {
            adj[i] = new ArrayList<>();
        }

    }
    static void add(int i, int j)
    {
        adj[i].add(j);
        adj[j].add(i);
    }
    public static void main(String[] args) {
        new Thread(null, new main(), "Check2", 1 << 26).start();// to increse stack size in java
    }
    static long mod = (long) (1e9 + 7);
    public void run() {
        InputReader in = new InputReader(System.in);
        PrintWriter w = new PrintWriter(System.out);

        int n=in.nextInt();
        int p=(int)pow(2,n+1);
        int a[]=new int[p];
        for(int i=2;i<=p-1;i++)
        {
            a[i]=in.nextInt();

        }
        long ans=0;
        int val=(int)power(2,n-1);
        while (val>0){

            int j=val;
            int k=2*j-1;
            while (j<=k){
      //          System.out.println(j);
                int left=a[2*j];
                int right=a[2*j+1];
                ans=ans+abs(left-right);

                a[j]+=max(left,right);
                j++;
            }

            val/=2;
        }
        w.println(ans);

        w.close();

    }
    static void diji(int s,long dist[],ArrayList <pair> adj[]){
        dist[s]=0;
        PriorityQueue <pair> q=new PriorityQueue<>(new cmp());
        q.add(new pair(s,0));
        while (!q.isEmpty())
        {
            pair p1=q.poll();
            for(pair ne:adj[p1.a]){

                if((long)p1.b+(long)ne.b<dist[ne.a]){
                    dist[ne.a]=(long)p1.b+(long)ne.b;
                    pair p2=new pair(ne.a,dist[ne.a]);
                    q.add(p2);
                }

            }
        }

    }
    static class cmp implements Comparator<pair>{

        public  int compare(pair o1,pair o2)
        {
            return o1.b<o2.b?-1:o1.b>o2.b?1:0;
        }

    }

    static class pair {
        int a;
        long b;
        pair(int a,long b){
            this.a=a;
            this.b=b;
        }
        public boolean equals(Object obj) {      //  override equals method for object to remove tem from arraylist and sets etc.......
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            pair other = (pair) obj;
            if (b!= other.b||a!=other.a)
                return false;
            return true;
        }
    }

    static long modinv(long a,long b)
    {
        long p=power(b,mod-2);

        p=a%mod*p%mod;
        p%=mod;

        return p;

    }

    static long power(long x,long y){
        if(y==0)return 1%mod;
        if(y==1)return x%mod;

        long res=1;
        x=x%mod;
        while(y>0){

            if((y%2)!=0){
                res=(res*x)%mod;
            }

            y=y/2;
            x=(x*x)%mod;
        }

        return res;

    }
    static  int gcd(int a,int b){

        if(b==0)return a;
        return gcd(b,a%b);
    }

    static  void sev(int a[],int n){

        for(int i=2;i<=n;i++)a[i]=i;
        for(int i=2;i<=n;i++){

            if(a[i]!=0){
                for(int j=2*i;j<=n;){

                    a[j]=0;
                    j=j+i;
                }
            }

        }

    }

    static class node{

        int y;
        int val;

        node(int a,int b){

            y=a;
            val=b;

        }

    }

    static class InputReader
    {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream)
        {
            this.stream = stream;
        }

        public int read()
        {
            if (numChars==-1)
                throw new InputMismatchException();

            if (curChar >= numChars)
            {
                curChar = 0;
                try
                {
                    numChars = stream.read(buf);
                }
                catch (IOException e)
                {
                    throw new InputMismatchException();
                }

                if(numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public String nextLine()
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
        public int nextInt()
        {
            int c = read();

            while(isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-')
            {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do
            {
                if(c<'0'||c>'9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
            return res * sgn;
        }

        public double nextDouble()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.')
            {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.')
            {
                c = read();
                double m = 1;
                while (!isSpaceChar(c))
                {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = read();
            }
            while (!isSpaceChar(c));

            return res.toString();
        }

        public boolean isSpaceChar(int c)
        {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next()
        {
            return readString();
        }

        public interface SpaceCharFilter
        {
            public boolean isSpaceChar(int ch);
        }
    }

}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author madi.sagimbekov
 */
public class C526B {

    private static BufferedReader in;
    private static BufferedWriter out;

    private static List<Integer>[] list;
    private static int[] arr;
    private static int[][] dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    private static boolean[] used;

    public static void main(String[] args) throws IOException {
        open();

        int n = readInt();
        int[] x = readInts();
        int len = x.length + 2;

        int[] a = new int[len];
        for (int i = 2; i < len; i++) {
            a[i] = x[i - 2];
        }

        int ans = 0;
        for (int i = len - 1; i >= 2; i -= 2) {
            ans += Math.abs(a[i] - a[i - 1]);
            a[i / 2] += Math.max(a[i], a[i - 1]);
        }

        out.write(ans + "\n");

        close();
    }

    private static int[] readInts() throws IOException {
        return Stream.of(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
    }

    private static int readInt() throws IOException {
        return Integer.parseInt(in.readLine());
    }

    private static long[] readLongs() throws IOException {
        return Stream.of(in.readLine().split(" ")).mapToLong(Long::parseLong).toArray();
    }

    private static long readLong() throws IOException {
        return Long.parseLong(in.readLine());
    }

    private static double[] readDoubles() throws IOException {
        return Stream.of(in.readLine().split(" ")).mapToDouble(Double::parseDouble).toArray();
    }

    private static double readDouble() throws IOException {
        return Double.parseDouble(in.readLine());
    }

    private static String readString() throws IOException {
        return in.readLine();
    }

    private static List<Integer>[] buildAdjacencyList(int n, int m) throws IOException {
        List<Integer>[] list = new ArrayList[n + 1];
        for (int i = 0; i <= n; i++) {
            list[i] = new ArrayList<>();
        }

        for (int i = 0; i < m; i++) {
            int[] e = readInts();
            list[e[0]].add(e[1]);
            list[e[1]].add(e[0]);
        }

        return list;
    }

    private static void open() {
        in = new BufferedReader(new InputStreamReader(System.in));
        out = new BufferedWriter(new OutputStreamWriter((System.out)));
    }

    private static void close() throws IOException {
        out.flush();
        out.close();
        in.close();
    }

}


import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Random;
import java.io.Writer;
import java.util.List;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Alex
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskB solver = new TaskB();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskB {
    public void solve(int testNumber, InputReader in, OutputWriter out){
	    int n = in.ri();
	    int[] a = IOUtils.readIntArray(in, (int) IntegerUtils.power(2, n + 1) - 2);
	    int start = (int) ArrayUtils.sumArray(a);
	    int[] acopy = Arrays.copyOf(a, a.length);
	    int startindex = (int) IntegerUtils.power(2, n) - 2;
	    for(int i = startindex; i < acopy.length; i+=2) {
		    acopy[i] = Math.max(acopy[i], acopy[i + 1]);
		    acopy[i + 1] = acopy[i];
	    }
	    for(int level = n - 2; level >= 0; level--) {
		    startindex = (int) IntegerUtils.power(2, level+1) - 2;
		    int valuesatlevel = (int) IntegerUtils.power(2, level + 1);
		    for(int i = startindex; i < startindex + valuesatlevel; i+=2) {
			    int left = acopy[i] + acopy[(i + 1) * 2];
			    int right = acopy[i + 1] + acopy[(i + 2) * 2];
			    int need = Math.max(left, right);
			    acopy[i] = need - acopy[(i + 1) * 2];
			    acopy[i + 1] = need - acopy[(i + 2) * 2];
		    }
	    }
//	    for(int x : acopy) out.print(x + " ");
	    int end = (int) ArrayUtils.sumArray(acopy);
	    out.print(end - start);
    }
}

class InputReader {
	private InputStream stream;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int numChars;
	private SpaceCharFilter filter;

	public InputReader(InputStream stream) {
		this.stream = stream;
	}

	public int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}
	public int ri(){
		return readInt();
	}

	public int readInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}
	public boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return isWhitespace(c);
	}

	public static boolean isWhitespace(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}
	public interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}
}

class OutputWriter {
	private final PrintWriter writer;

	public OutputWriter(OutputStream outputStream) {
		writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
	}
	public void close() {
		writer.close();
	}
	public void print(int i) {
		writer.print(i);
	}
}

class IOUtils {
	public static int[] readIntArray(InputReader in, int size) {
		int[] array = new int[size];
		for (int i = 0; i < size; i++)
			array[i] = in.readInt();
		return array;
	}
}

class IntegerUtils {
	public static long power(long base, long exponent) {
		if (exponent == 0)
			return 1;
		long result = power(base, exponent >> 1);
		result = result * result;
		if ((exponent & 1) != 0)
			result = result * base;
		return result;
	}
}

class ArrayUtils {
	public static long sumArray(int[] array) {
		long result = 0;
		for (int element : array)
			result += element;
		return result;
	}
}


import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.List;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Alex
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskB solver = new TaskB();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskB {
    public void solve(int testNumber, InputReader in, OutputWriter out){
	    int n = in.ri();
	    int[] a = IOUtils.readIntArray(in, (int) IntegerUtils.power(2, n + 1) - 2);
//	    int start = (int) ArrayUtils.sumArray(a);
	    int[] acopy = Arrays.copyOf(a, a.length);
//	    int res = 0;
	    int startindex = (int) IntegerUtils.power(2, n) - 2;
	    for(int i = startindex; i < acopy.length; i+=2) {
		    acopy[i] = Math.max(acopy[i], acopy[i + 1]);
		    acopy[i + 1] = acopy[i];
//		    res += Math.abs(acopy[i] - a[i]);
//		    res += Math.abs(acopy[i] - a[i+1]);
	    }
	    for(int level = n - 2; level >= 0; level--) {
		    startindex = (int) IntegerUtils.power(2, level+1) - 2;
		    int valuesatlevel = (int) IntegerUtils.power(2, level + 1);
		    for(int i = startindex; i < startindex + valuesatlevel; i+=2) {
			    int left = acopy[i] + acopy[(i + 1) * 2];
			    int right = acopy[i + 1] + acopy[(i + 2) * 2];
			    int need = Math.max(left, right);

//			    acopy[i] = need - acopy[(i + 1) * 2];
//			    acopy[i + 1] = need - acopy[(i + 2) * 2];
			    acopy[i] = acopy[i + 1] = need;
		    }
	    }
//	    for(int x : acopy) out.print(x + " ");
//	    out.printLine();
//	    int end = (int) ArrayUtils.sumArray(acopy);
//	    out.printLine(end - start);
//	    out.printLine(res);
	    int resres = 0;
	    for(int i = 0; i < a.length; i++) {
		    int newval = acopy[i];
		    int childindex = (i + 1) * 2;
		    if (childindex < a.length) newval -= acopy[childindex];
		    int change = (newval - a[i]);
//		    out.print(change + " ");
		    resres += change;
	    }
//	    out.printLine();
	    out.printLine(resres);
    }
}

class InputReader {
	private InputStream stream;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int numChars;
	private SpaceCharFilter filter;

	public InputReader(InputStream stream) {
		this.stream = stream;
	}

	public int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}
	public int ri(){
		return readInt();
	}

	public int readInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}
	public boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return isWhitespace(c);
	}

	public static boolean isWhitespace(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}
	public interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}
}

class OutputWriter {
	private final PrintWriter writer;

	public OutputWriter(OutputStream outputStream) {
		writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
	}
	public void close() {
		writer.close();
	}
	public void printLine(int i) {
		writer.println(i);
	}

}

class IOUtils {
	public static int[] readIntArray(InputReader in, int size) {
		int[] array = new int[size];
		for (int i = 0; i < size; i++)
			array[i] = in.readInt();
		return array;
	}
}

class IntegerUtils {
	public static long power(long base, long exponent) {
		if (exponent == 0)
			return 1;
		long result = power(base, exponent >> 1);
		result = result * result;
		if ((exponent & 1) != 0)
			result = result * base;
		return result;
	}
}


//package codeforces;
import java.io.*;
import java.util.*;
public class Omnomanddarkpark {
public static void main(String[] args) throws Exception
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pw=new PrintWriter(System.out);
    int n=Integer.parseInt(br.readLine());
    int edge=(int)2*((int)Math.pow(2,n)-1);
    int[] a=new int[edge+10];
    StringTokenizer st1=new StringTokenizer(br.readLine());
    for(int i=0;i<edge;i++)
    {
        a[i]=Integer.parseInt(st1.nextToken());
    }
    //pw.println("edge is"+edge);
    nade[] arr=new nade[edge+2];
    int ans=0;
    for(int i=0;i<edge+2;i++)
    {
        arr[i]=new nade();
    }
    for(int i=edge/2;i>=1;i--)
    {
        pw.println("i is"+i);
        int lnade=2*i;
        int rnade=2*i+1;
        int leftmax=arr[lnade].value+a[lnade-2];
        int rightmax=arr[rnade].value+a[lnade-1];
        //pw.println("leftmax is"+leftmax+" right max is"+rightmax);
        arr[i].value=Math.max(leftmax, rightmax);
        ans+=Math.abs(leftmax-rightmax);

    }
    pw.println(ans);
    pw.close();

}

}
class nade
{
    int value;
    public nade()
    {
    value=0;
    }
}


//package codeforces;
import java.io.*;
import java.util.*;
public class Omnomanddarkpark {
public static void main(String[] args) throws Exception
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pw=new PrintWriter(System.out);
    int n=Integer.parseInt(br.readLine());
    int edge=(int)2*((int)Math.pow(2,n)-1);
    int[] a=new int[edge+10];
    StringTokenizer st1=new StringTokenizer(br.readLine());
    for(int i=0;i<edge;i++)
    {
        a[i]=Integer.parseInt(st1.nextToken());
    }
    //pw.println("edge is"+edge);
    nade[] arr=new nade[edge+2];
    int ans=0;
    for(int i=0;i<edge+2;i++)
    {
        arr[i]=new nade();
    }
    for(int i=edge/2;i>=1;i--)
    {
        //pw.println("i is"+i);
        int lnade=2*i;
        int rnade=2*i+1;
        int leftmax=arr[lnade].value+a[lnade-2];
        int rightmax=arr[rnade].value+a[lnade-1];
        //pw.println("leftmax is"+leftmax+" right max is"+rightmax);
        arr[i].value=Math.max(leftmax, rightmax);
        ans+=Math.abs(leftmax-rightmax);

    }
    pw.println(ans);
    pw.close();

}

}
class nade
{
    int value;
    public nade()
    {
    value=0;
    }
}


import java.io.*;
import java.math.BigInteger;
import java.util.*;

public class Main {
	static int m=100000007;
	//static int count=1;
	static int count=0;
	static  int[][] pre;
	static ArrayList<Pair> ar=new ArrayList<Pair>();
		public static void main(String[] args) throws IOException
		{
		InputReader in = new InputReader(System.in);
		PrintWriter pw = new PrintWriter(System.out);
		PriorityQueue<Integer> heap=new PriorityQueue<Integer>();
	    int n=in.nextInt();

	    int a[]=new int[(int)Math.pow(2,n+1)];
	    for(int i=2;i<=(int)Math.pow(2,n+1)-1;i++)
	    	a[i]=in.nextInt();
	    int ans=0;
	    for(int i=(int)Math.pow(2,n)-1;i>=1;i--)
	    {
	    	int left=a[2*i];
	    	int right=a[2*i+1];
	    	ans+=(2*Math.max(left, right))-left-right;
	    	a[i]+=Math.max(left, right);
	    }
	    System.out.println(ans);
		}

	    private static void dfs(int i, ArrayList<Integer>[] adj, boolean[] vis) {
			vis[i]=true;
			count++;
			for(int j=0;j<adj[i].size();j++)
            if(!vis[adj[i].get(j)])
            	dfs(adj[i].get(j),adj,vis);
 	    }

		public static long power(long a,long b)
		{
			long result=1;
			while(b>0)
			{
				if(b%2==1)
					result*=a;
				a=a*a;
				b/=2;
			}
			return result;
		}
		public static boolean IsPrime(long n)
		{
	        // Corner cases
	        if (n <= 1)
	            return false;
	        if (n <= 3)
	            return true;

	        // This is checked so that we can skip
	        // middle five numbers in below loop
	        if (n % 2 == 0 || n % 3 == 0)
	            return false;

	        for (int i = 5; i * i <= n; i = i + 6)
	            if (n % i == 0 || n % (i + 2) == 0)
	                return false;

	        return true;
	    }
		public static long pow(long n,long p,long m)
	{
		 long  result = 1;
		  if(p==0)
		    return 1;
		if (p==1)
		    return n;
		while(p!=0)
		{
		    if(p%2==1)
		        result *= n;
		    if(result>=m)
		    result%=m;
		    p >>=1;
		    n*=n;
		    if(n>=m)
		    n%=m;
		}
		return result;
	}
	static class Pair implements Comparable<Pair>{
		int val;
		int fr;
		Pair(int mr,int er){
			val=mr;
			fr=er;

		}
		@Override
		public int compareTo(Pair o) {
			return 1;
			}
	}
	public static long gcd(long a, long b) {
		  if (b == 0) return a;
		  return gcd(b, a%b);
		}
	static class InputReader {

		private InputStream stream;
		private byte[] buf = new byte[8192];
		private int curChar, snumChars;
		private SpaceCharFilter filter;

		public InputReader(InputStream stream) {
			this.stream = stream;
		}

		public int snext() {
			if (snumChars == -1)
				throw new InputMismatchException();
			if (curChar >= snumChars) {
				curChar = 0;
				try {
					snumChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (snumChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		public   int nextInt() {
			int c = snext();
			while (isSpaceChar(c))
				c = snext();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = snext();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = snext();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public long nextLong() {
			int c = snext();
			while (isSpaceChar(c))
				c = snext();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = snext();
			}
			long res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = snext();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int[] nextIntArray(int n) {
			int a[] = new int[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

		public String readString() {
			int c = snext();
			while (isSpaceChar(c))
				c = snext();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = snext();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public boolean isSpaceChar(int c) {
			if (filter != null)
				return filter.isSpaceChar(c);
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		public interface SpaceCharFilter {
			public boolean isSpaceChar(int ch);
		}
	}
}


import java.util.ArrayList;
import java.util.Scanner;

public class cf526b {
    public static int n;
    public static ArrayList<Integer>[] roads;
    public static ArrayList<Integer> lengths;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        int pow = 2;
        roads = new ArrayList[n];
        lengths = new ArrayList<>();
        int changes = 0;
        for(int i=0;i<n-1;i++){
            roads[i]=new ArrayList<>();
            for(int j=0;j<pow;j++){
                roads[i].add(in.nextInt());
            }
            pow <<= 1;
        }
        pow >>=1;
        roads[n-1]=new ArrayList<>();
        for(int j=0;j<pow;j++){
            int valA = in.nextInt();
            int valB = in.nextInt();
            if(valA>valB){
                roads[n-1].add(valA);
                roads[n-1].add(valA);
                changes+=valA-valB;
            }else{
                roads[n-1].add(valB);
                roads[n-1].add(valB);
                changes+=valB-valA;
            }
        }
        for(int i=n-2;i>=0;i--){
            for(int j=0;j<pow;j+=2){
                int valA = sumBelow(i,j);//roads[i].get(j)+difFromBelow;
                int valB = sumBelow(i, j + 1);//roads[i].get(j+1);
                //System.out.println(i+" "+j+" - "+valA+" "+valB);
                if(valA>valB){
                    //roads[i].set(j,valA);
                    roads[i].set(j+1,roads[i].get(j+1)+valA-valB);
                    changes+=valA-valB;
                }else{
                    roads[i].set(j,roads[i].get(j)+valB-valA);
                    //roads[i].set(j+1,valB);
                    changes+=valB-valA;
                }
            }
            pow >>= 1;
        }
        System.out.println(changes);
        in.close();
    }

    public static int sumBelow(int level, int pos){
        int result;
        if(level==n-1){
            result = roads[level].get(pos);
        }else {
            result =roads[level].get(pos)+ sumBelow(level + 1,pos <<1);
        }
        return result;
    }

    public static void countLenghts(int level, int pos, int sum){
        if(level<n-1) {
            for (int i = pos; i < pos+2; i++) {
                countLenghts(level+1,i<<1,sum+roads[level].get(i));
            }
        }else{
            for (int i = pos; i < pos+2; i++) {
                lengths.add(sum + roads[level].get(i));
            }
        }
    }

    public static int checkLengths(){
        int longest = lengths.get(0);
        boolean equal=true;
        for(int i=1;i<lengths.size();i++){
            if(lengths.get(i)!=longest){
                equal = false;
            }
            if(lengths.get(i)>longest){
                longest=lengths.get(i);
            }
        }
        if(equal) {
            return 0;
        }else{
            return longest;
        }
    }
}


import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Egor Zhdan
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		IOReader in = new IOReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskB solver = new TaskB();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskB {

    public void solve(int testNumber, IOReader in, PrintWriter out) {
        n = in.nextInt();
        a = in.readIntArray((1 << (n + 1)) - 2);
        go(1, 0);
        out.println(answer);
    }

    int n;
    int[] a;
    long answer = 0;

    int go(int v, int d) {
        if (d == n) {
            return 0;
        }
        int g1 = go(2 * v, d + 1) + a[2 * v - 2];
        int g2 = go(2 * v + 1, d + 1) + a[2 * v - 1];
        answer += Math.abs(g1 - g2);
        return Math.max(g1, g2);
    }

}

class IOReader {

    private BufferedReader reader;
    private StringTokenizer tokenizer;

    public String nextToken() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return tokenizer.nextToken();
    }

    public int nextInt() {
        return Integer.parseInt(nextToken());
    }

    public int[] readIntArray(int count) {
        int[] array = new int[count];
        for (int i = 0; i < count; i++) {
            array[i] = nextInt();
        }
        return array;
    }

    public IOReader(InputStream stream) {
        reader = new BufferedReader(new InputStreamReader(stream));
    }

}


import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Egor Zhdan
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		IOReader in = new IOReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskB solver = new TaskB();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskB {

    public void solve(int testNumber, IOReader in, PrintWriter out) {
        n = in.nextInt();
        a = in.readIntArray((1 << (n + 1)) - 2);
        if (n == 1) {
            out.println(0);
        } else {
            go(1, 0);
            out.println(answer);
        }
    }

    int n;
    int[] a;
    long answer = 0;

    int go(int v, int d) {
        if (d == n) {
            return 0;
        }
        int g1 = go(2 * v, d + 1) + a[2 * v - 2];
        int g2 = go(2 * v + 1, d + 1) + a[2 * v - 1];
        answer += Math.abs(g1 - g2);
        return Math.max(g1, g2);
    }

}

class IOReader {

    private BufferedReader reader;
    private StringTokenizer tokenizer;

    public String nextToken() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return tokenizer.nextToken();
    }

    public int nextInt() {
        return Integer.parseInt(nextToken());
    }

    public int[] readIntArray(int count) {
        int[] array = new int[count];
        for (int i = 0; i < count; i++) {
            array[i] = nextInt();
        }
        return array;
    }

    public IOReader(InputStream stream) {
        reader = new BufferedReader(new InputStreamReader(stream));
    }

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Random;
import java.util.StringTokenizer;

public class ZCRB {

  static BufferedReader in;
  static PrintWriter out;
  static StringTokenizer tok;

  static void solve() throws Exception {
    int n = nextInt();
    long[] max = new long[(1 << (n + 1)) - 1];
    long[] edge = nextLongArray((1 << (n + 1)) - 2, 0);
    for (int i = (1 << n) - 2; i >= 0; i--)
      max[i] = Math.max(max[i * 2 + 1], max[i * 2 + 2]) + Math.max(edge[i * 2], edge[i * 2 + 1]);
    long ans = 0;
    for (int i = 0; i < (1 << n) - 1; i++) {
      ans += max[i] - max[i * 2 + 1] - edge[i * 2];
      ans += max[i] - max[i * 2 + 2] - edge[i * 2 + 1];
    }
    out.println(ans);
  }

  public static void main(String args[]) {
    try {
      in = new BufferedReader(new InputStreamReader(System.in));
      out = new PrintWriter(new OutputStreamWriter(System.out));
      solve();
      in.close();
      out.close();
    } catch (Throwable e) {
      e.printStackTrace();
      System.exit(1);
    }
  }

  static int nextInt() throws IOException {
    return Integer.parseInt(next());
  }

  static int[] nextIntArray(int len, int start) throws IOException {
    int[] a = new int[len];
    for (int i = start; i < len; i++)
      a[i] = nextInt();
    return a;
  }

  static long nextLong() throws IOException {
    return Long.parseLong(next());
  }

  static long[] nextLongArray(int len, int start) throws IOException {
    long[] a = new long[len];
    for (int i = start; i < len; i++)
      a[i] = nextLong();
    return a;
  }

  static double nextDouble() throws IOException {
    return Double.parseDouble(next());
  }

  static double[] nextDoubleArray(int len, int start) throws IOException {
    double[] a = new double[len];
    for (int i = start; i < len; i++)
      a[i] = nextDouble();
    return a;
  }

  static BigInteger nextBigInteger() throws IOException {
    return new BigInteger(next());
  }

  static String next() throws IOException {
    while (tok == null || !tok.hasMoreTokens()) {
      tok = new StringTokenizer(in.readLine());
    }
    return tok.nextToken();
  }

  static String nextLine() throws IOException {
    tok = new StringTokenizer("");
    return in.readLine();
  }

  static void shuffleArray(long[] array) {
    Random random = new Random();
    for (int i = array.length - 1; i > 0; i--) {
      int index = random.nextInt(i + 1);
      long temp = array[index];
      array[index] = array[i];
      array[i] = temp;
    }
  }

  static boolean hasNext() throws IOException {
    while (tok == null || !tok.hasMoreTokens()) {
      String s = in.readLine();
      if (s == null) {
        return false;
      }
      tok = new StringTokenizer(s);
    }
    return true;
  }

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Random;
import java.util.StringTokenizer;

public class ZCRB {

  static BufferedReader in;
  static PrintWriter out;
  static StringTokenizer tok;

  static void solve() throws Exception {
    int n = nextInt();
    long[] max = new long[(1 << (n + 1)) - 1];
    long[] edge = nextLongArray((1 << (n + 1)) - 2, 0);
    for (int i = (1 << n) - 2; i >= 0; i--)
      max[i] = Math.max(max[i * 2 + 1] + edge[i * 2], max[i * 2 + 2] + edge[i * 2 + 1]);
    long ans = 0;
    for (int i = 0; i < (1 << n) - 1; i++) {
      ans += max[i] - max[i * 2 + 1] - edge[i * 2];
      ans += max[i] - max[i * 2 + 2] - edge[i * 2 + 1];
    }
    out.println(ans);
  }

  public static void main(String args[]) {
    try {
      in = new BufferedReader(new InputStreamReader(System.in));
      out = new PrintWriter(new OutputStreamWriter(System.out));
      solve();
      in.close();
      out.close();
    } catch (Throwable e) {
      e.printStackTrace();
      System.exit(1);
    }
  }

  static int nextInt() throws IOException {
    return Integer.parseInt(next());
  }

  static int[] nextIntArray(int len, int start) throws IOException {
    int[] a = new int[len];
    for (int i = start; i < len; i++)
      a[i] = nextInt();
    return a;
  }

  static long nextLong() throws IOException {
    return Long.parseLong(next());
  }

  static long[] nextLongArray(int len, int start) throws IOException {
    long[] a = new long[len];
    for (int i = start; i < len; i++)
      a[i] = nextLong();
    return a;
  }

  static double nextDouble() throws IOException {
    return Double.parseDouble(next());
  }

  static double[] nextDoubleArray(int len, int start) throws IOException {
    double[] a = new double[len];
    for (int i = start; i < len; i++)
      a[i] = nextDouble();
    return a;
  }

  static BigInteger nextBigInteger() throws IOException {
    return new BigInteger(next());
  }

  static String next() throws IOException {
    while (tok == null || !tok.hasMoreTokens()) {
      tok = new StringTokenizer(in.readLine());
    }
    return tok.nextToken();
  }

  static String nextLine() throws IOException {
    tok = new StringTokenizer("");
    return in.readLine();
  }

  static void shuffleArray(long[] array) {
    Random random = new Random();
    for (int i = array.length - 1; i > 0; i--) {
      int index = random.nextInt(i + 1);
      long temp = array[index];
      array[index] = array[i];
      array[i] = temp;
    }
  }

  static boolean hasNext() throws IOException {
    while (tok == null || !tok.hasMoreTokens()) {
      String s = in.readLine();
      if (s == null) {
        return false;
      }
      tok = new StringTokenizer(s);
    }
    return true;
  }

}


import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Stanislav Pak
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskB solver = new TaskB();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskB {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
		int n = in.readInt();
		int m = (1 << (n + 1)) - 1;
		int[] a = new int[m];
		for (int i = 1; i < m; ++i) {
			a[i] = in.readInt();
		}
		long[] count = new long[m];
		long[] add = new long[m];
		for (int i = m / 2 - 1; i >= 0; --i) {
			int l = (i << 1) + 1;
			int r = (i + 1) << 1;
			long mx = Math.max(count[l] + a[l], count[r] + a[r]);
			add[i] = mx - count[l] - a[l];
			add[i] += mx - count[r] - a[r];
			count[i] = mx;
			add[i] += add[l];
			add[i] += add[r];
		}
		out.printLine(add[0]);
    }
}

class InputReader {

	private InputStream stream;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int numChars;
	private SpaceCharFilter filter;

	public InputReader(InputStream stream) {
		this.stream = stream;
	}

	public int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int readInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return isWhitespace(c);
	}

	public static boolean isWhitespace(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	public interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}
}

class OutputWriter {
	private final PrintWriter writer;

	public OutputWriter(OutputStream outputStream) {
		writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
	}

	public void close() {
		writer.close();
	}

	public void printLine(long i) {
		writer.println(i);
	}

}


import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Stanislav Pak
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskB solver = new TaskB();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskB {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
		int n = in.readInt();
		int m = (1 << (n + 1)) - 1;
		int[] a = new int[m];
		for (int i = 1; i < m; ++i) {
			a[i] = in.readInt();
		}
		long[] count = new long[m];
		long[] add = new long[m];
		for (int i = m - 1; i >= m / 2; --i) {
			count[i] = a[i];
			add[i] = 0;
		}
		for (int i = m / 2 - 1; i >= 0; --i) {
			int l = (i << 1) + 1;
			int r = (i + 1) << 1;
			long mx = Math.max(count[l] + a[l], count[r] + a[r]);
			add[i] = mx - count[l] - a[l];
			add[i] += mx - count[r] - a[r];
			count[i] = mx;
		}
		out.printLine(add[0]);
    }
}

class InputReader {

	private InputStream stream;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int numChars;
	private SpaceCharFilter filter;

	public InputReader(InputStream stream) {
		this.stream = stream;
	}

	public int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int readInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return isWhitespace(c);
	}

	public static boolean isWhitespace(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	public interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}
}

class OutputWriter {
	private final PrintWriter writer;

	public OutputWriter(OutputStream outputStream) {
		writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
	}

	public void close() {
		writer.close();
	}

	public void printLine(long i) {
		writer.println(i);
	}

}


import java.util.Scanner;

public class B526 {

	private static void solve(){
		Scanner in=new Scanner(System.in);
		int n=in.nextInt();
		int l=(1<<(n+1));
		int[] a=new int[l];
		for(int i=2;i<a.length;++i){
			a[i]=in.nextInt();
		}
			int ans =0;
			for( int i=(1<<n)-1;i>=1;--i){
				ans+=Math.abs(a[2*i]-a[2*i+1]);
				a[i]+=Math.max(a[2*i], a[2*i+1]);
			}
			System.out.println(ans);
		}

	public static void main(String[] args) {
		new B526().solve();

	}

}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.lang.Long;
import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * Problem statement: http://codeforces.com/problemset/problem/491/A
 *
 * @author thepham
 *
 */
public class B_Zepto2015 {

    static long Mod = 1000000007;

    public static void main(String[] args) throws FileNotFoundException {
        // PrintWriter out = new PrintWriter(new FileOutputStream(new File(
        // "output.txt")));
        PrintWriter out = new PrintWriter(System.out);
        Scanner in = new Scanner();
        int n = in.nextInt();
        int[] data = new int[(int) Math.pow(2, (n + 1)) - 2];
        for (int i = 0; i < data.length; i++) {
            data[i] = in.nextInt();
        }
        int[] min = new int[(int) Math.pow(2, n + 1)];
        Arrays.fill(min, Integer.MAX_VALUE);
        int[] max = new int[min.length];
        for (int i = data.length + 1; i >= 2; i--) {
            int index = i / 2;
            if (i < min.length && min[i] != Integer.MAX_VALUE) {
                min[index] = Math.min(data[i - 2] + min[i], min[ index]);
            } else {
                min[index] = Math.min(data[i - 2], min[index]);
            }
            max[index] = Math.max(data[i - 2] + max[i], max[index]);

        }
        int result = Integer.MAX_VALUE;
        for(int i = max[1]; i <= 200; i++){
            boolean ok = true;
            int[]total = new int[min.length + 2];
            int tmp = 0;
            for(int j = 2; j <= data.length + 1; j++){
                if(j >= max.length ){
                    break;
                }
                int need = i - total[j/2] - data[j - 2] - max[j];
               // System.out.println(need + total[j/2] + " " + data[j - 2] + " " + max[j]);
                if(need < 0){
                    ok = false;
                    break;
                }
                total[j] += need + data[j - 2];
                tmp += need;
            }
            if(ok){
                result = Math.min(result, tmp);
            }
        }
        out.println(result);
        out.close();
    }

    public static int[] buildKMP(String val) {
        int[] data = new int[val.length() + 1];
        int i = 0;
        int j = -1;
        data[0] = -1;
        while (i < val.length()) {
            while (j >= 0 && val.charAt(i) != val.charAt(j)) {
                j = data[j];
            }
            i++;
            j++;

            data[i] = j;
            // System.out.println(val + " " + i + " " + data[i]);
        }
        return data;
    }

    static int find(int index, int[] u) {
        if (u[index] != index) {
            return u[index] = find(u[index], u);
        }
        return index;
    }

    static int crossProduct(Point a, Point b) {
        return a.x * b.y + a.y * b.x;
    }

    static long squareDist(Point a) {
        long x = a.x;
        long y = a.y;
        return x * x + y * y;
    }

    static Point minus(Point a, Point b) {
        return new Point(a.x - b.x, a.y - b.y);
    }

    public static boolean nextPer(int[] data) {
        int i = data.length - 1;
        while (i > 0 && data[i] < data[i - 1]) {
            i--;
        }
        if (i == 0) {
            return false;
        }
        int j = data.length - 1;
        while (data[j] < data[i - 1]) {
            j--;
        }
        int temp = data[i - 1];
        data[i - 1] = data[j];
        data[j] = temp;
        Arrays.sort(data, i, data.length);
        return true;
    }

    static class Point {

        int x, y;

        public Point(int x, int y) {
            super();
            this.x = x;
            this.y = y;
        }

        public String toString() {
            return "{" + x + " " + y + "}";
        }
    }

    static long gcd(long a, long b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    public static class FT {

        int[] data;

        FT(int n) {
            data = new int[n];
        }

        public void update(int index, int value) {
            while (index < data.length) {
                data[index] += value;
                index += (index & (-index));
            }
        }

        public int get(int index) {
            int result = 0;
            while (index > 0) {
                result += data[index];
                index -= (index & (-index));
            }
            return result;

        }
    }

    static class Scanner {

        BufferedReader br;
        StringTokenizer st;

        public Scanner() throws FileNotFoundException {
            // System.setOut(new PrintStream(new
            // BufferedOutputStream(System.out), true));
            br = new BufferedReader(new InputStreamReader(System.in));
            // br = new BufferedReader(new InputStreamReader(new
            // FileInputStream(
            // new File("input.txt"))));
        }

        public String next() {

            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (Exception e) {
                    throw new RuntimeException();
                }
            }
            return st.nextToken();
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public double nextDouble() {
            return Double.parseDouble(next());
        }

        public String nextLine() {
            st = null;
            try {
                return br.readLine();
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }

        public boolean endLine() {
            try {
                String next = br.readLine();
                while (next != null && next.trim().isEmpty()) {
                    next = br.readLine();
                }
                if (next == null) {
                    return true;
                }
                st = new StringTokenizer(next);
                return st.hasMoreTokens();
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    }
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.lang.Long;
import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * Problem statement: http://codeforces.com/problemset/problem/491/A
 *
 * @author thepham
 *
 */
public class B_Zepto2015 {

    static long Mod = 1000000007;

    public static void main(String[] args) throws FileNotFoundException {
        // PrintWriter out = new PrintWriter(new FileOutputStream(new File(
        // "output.txt")));
        PrintWriter out = new PrintWriter(System.out);
        Scanner in = new Scanner();
        int n = in.nextInt();
        int[] data = new int[(int) Math.pow(2, (n + 1)) - 2];
        for (int i = 0; i < data.length; i++) {
            data[i] = in.nextInt();
        }
        int v = max(0, data);
       // System.out.println(v);
        out.println(cal(v, 0, data));
        out.close();
    }

    public static int cal(int left, int node, int[] data) {
        if (2 * node + 1 >= data.length) {
            return 0;
        }
        int result = 0;
        int x = max(node * 2 + 1, data);
        result += left - data[2 * node] - x;
        int y = max(node * 2 + 2, data);
       // System.out.println(x + " " + y + " " + node);
        result += left - data[2 * node + 1] - y;
        result += cal(left - data[2 * node] - (left - data[ 2 * node] - x), node * 2 + 1, data);
        result += cal(left - data[ 2 * node + 1] - (left - data[2 * node + 1] - y), node * 2 + 2, data);
        return result;
    }

    public static int min(int node, int[] data) {
        if (2 * node + 1 >= data.length) {
            return 0;
        }
        int x = min(node * 2 + 1, data);
        int y = min(node * 2 + 2, data);
        return Math.min(x + data[2 * node], y + data[2 * node + 1]);
    }

    public static int max(int node, int[] data) {
        if (2 * node + 1 >= data.length) {
            return 0;
        }
        int x = max(node * 2 + 1, data);
        int y = max(node * 2 + 2, data);
        return Math.max(x + data[2 * node], y + data[2 * node + 1]);
    }

    public static int[] buildKMP(String val) {
        int[] data = new int[val.length() + 1];
        int i = 0;
        int j = -1;
        data[0] = -1;
        while (i < val.length()) {
            while (j >= 0 && val.charAt(i) != val.charAt(j)) {
                j = data[j];
            }
            i++;
            j++;

            data[i] = j;
            // System.out.println(val + " " + i + " " + data[i]);
        }
        return data;
    }

    static int find(int index, int[] u) {
        if (u[index] != index) {
            return u[index] = find(u[index], u);
        }
        return index;
    }

    static int crossProduct(Point a, Point b) {
        return a.x * b.y + a.y * b.x;
    }

    static long squareDist(Point a) {
        long x = a.x;
        long y = a.y;
        return x * x + y * y;
    }

    static Point minus(Point a, Point b) {
        return new Point(a.x - b.x, a.y - b.y);
    }

    public static boolean nextPer(int[] data) {
        int i = data.length - 1;
        while (i > 0 && data[i] < data[i - 1]) {
            i--;
        }
        if (i == 0) {
            return false;
        }
        int j = data.length - 1;
        while (data[j] < data[i - 1]) {
            j--;
        }
        int temp = data[i - 1];
        data[i - 1] = data[j];
        data[j] = temp;
        Arrays.sort(data, i, data.length);
        return true;
    }

    static class Point {

        int x, y;

        public Point(int x, int y) {
            super();
            this.x = x;
            this.y = y;
        }

        public String toString() {
            return "{" + x + " " + y + "}";
        }
    }

    static long gcd(long a, long b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    public static class FT {

        int[] data;

        FT(int n) {
            data = new int[n];
        }

        public void update(int index, int value) {
            while (index < data.length) {
                data[index] += value;
                index += (index & (-index));
            }
        }

        public int get(int index) {
            int result = 0;
            while (index > 0) {
                result += data[index];
                index -= (index & (-index));
            }
            return result;

        }
    }

    static class Scanner {

        BufferedReader br;
        StringTokenizer st;

        public Scanner() throws FileNotFoundException {
            // System.setOut(new PrintStream(new
            // BufferedOutputStream(System.out), true));
            br = new BufferedReader(new InputStreamReader(System.in));
            // br = new BufferedReader(new InputStreamReader(new
            // FileInputStream(
            // new File("input.txt"))));
        }

        public String next() {

            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (Exception e) {
                    throw new RuntimeException();
                }
            }
            return st.nextToken();
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public double nextDouble() {
            return Double.parseDouble(next());
        }

        public String nextLine() {
            st = null;
            try {
                return br.readLine();
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }

        public boolean endLine() {
            try {
                String next = br.readLine();
                while (next != null && next.trim().isEmpty()) {
                    next = br.readLine();
                }
                if (next == null) {
                    return true;
                }
                st = new StringTokenizer(next);
                return st.hasMoreTokens();
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    }
}


import java.awt.Point;
import java.io.*;
import java.lang.Integer;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import java.util.ArrayDeque;

import static java.lang.Math.*;

public class Main {

    final boolean ONLINE_JUDGE = !new File("input.txt").exists();
    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

    void init() throws FileNotFoundException {
        if (ONLINE_JUDGE) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        } else {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        }
    }

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            tok = new StringTokenizer(in.readLine());
        }
        return tok.nextToken();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }

    public static void main(String[] args) {
        new Main().run();
        // Sworn to fight and die
    }

    public void run() {
        try {
            long t1 = System.currentTimeMillis();
            init();
            solve();
            out.close();
            long t2 = System.currentTimeMillis();
            System.err.println("Time = " + (t2 - t1));
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }

    class LOL implements Comparable<LOL> {
        long count;
        long type;

        public LOL(long time, long num) {
            this.count = time;
            this.type = num;
        }

        @Override
        public int compareTo(LOL o) {

            if (o.count != count)
                return (int) (o.count - count); // ---->
            return (int) (o.type - type); // <----
        }

    }

    public long gcd(long a, long b) {
        if (a % b == 0)
            return b;
        else
            return gcd(b, a % b);
    }

    public int gcd(int a, int b) {
        if (a % b == 0)
            return b;
        else
            return gcd(b, a % b);
    }

    boolean prime(int n) {
        for (int i = 2; i <= sqrt(n); i++)
            if (n % i == 0)
                return false;
        return true;
    }

    public void solve() throws IOException {
       int n = readInt();
        int ans = 0;
        int numRoads = (int)pow(2, n+1);
        int[] road = new int[numRoads];

        for(int i = 2; i < numRoads; i++) road[i] = readInt();

        for(int i = numRoads - 1; i > 1; i -= 2) {
            road[i / 2] += max(road[i], road[i - 1]);
            ans += 2 * max(road[i], road[i - 1]) -  road[i] - road[i - 1];
        }

        out.print(ans);
    }

}


import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;

public class B {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);

        int k = in.nextInt();
        int n = (1<<k)*2-1;
        int[] path = new int[n];
        for (int i = 1 ; i < n ; i++) {
            path[i] = in.nextInt();
        }

        int[] light = new int[n];
        dfs(light, path, 0);

        int low = (1<<k)-1;
        int max = 0;
        int[] add = new int[n];
        for (int l = low ; l < n ; l++) {
            max = Math.max(max, light[l]);
        }
        for (int l = low ; l < n ; l++) {
            add[l] = max - light[l];
        }

        for (int i = low-1 ; i >= 1 ; i--) {
            int take = Math.min(add[i * 2 + 1], add[i * 2 + 2]);
            add[i] = take;
            add[i*2+1] -= take;
            add[i*2+2] -= take;
        }

        int ans = 0;
        for (int i = 1 ; i < n ; i++) {
            ans += add[i];
        }
        out.println(ans);
        out.flush();
    }

    private static void dfs(int[] l, int[] path, int now) {
        if (now >= l.length) {
            return;
        }
        l[now] += path[now];
        if (now >= 1) {
            l[now] += l[(now-1)/2];
        }
        dfs(l, path, now*2+1);
        dfs(l, path, now*2+2);
    }

    static void debug(Object... o) {
        System.err.println(Arrays.deepToString(o));
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Find the length of all leaves.
 * Make all leaves' cost equal to the maximum.
 * Minimize cost by adding common cost at the upper level of tree
 * Created by Tejas on 02-07-2018.
 */
public class Main {

    static int[] a;

    static int totalLeaves;
    static int totalEdges;
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder stringBuilder = new StringBuilder();
        String temp[];
        int N = Integer.parseInt(bufferedReader.readLine());

        a=new int[(1<<(N+1))+1];
        temp=bufferedReader.readLine().split(" ");
        for(int i=2;i<(1<<(N+1));i++)
            a[i]=Integer.parseInt(temp[i-2]);

        solve(N);
    }

    private static void solve(int N) {

        int sum=0;
        for(int i=(1<<N)-1;i>=1;i--){
            sum+=Math.abs(a[2*i]-a[2*i+1]);
            a[i]+=Math.max(a[2*i],a[2*i+1]);
        }

        System.out.println(sum);
    }
}


import java.util.*;
import java.io.*;

public class a{
    static List<Integer> [] al;
    static int [] value;
    static int ans=0;

    static void dfs(int u,int p){
        List<Integer> list=new ArrayList<>();
        int max=0;
        for(int v : al[u]){
            if(v!=p){
                dfs(v,u);
                max=Math.max(max,value[v]);
                list.add(value[v]);
            }
        }
        for(int i : list)ans+=(max-i);
        value[u]+=max;
    }
    public static void main(String [] args) throws IOException{
        FastScanner sc=new FastScanner();
        int n=sc.nextInt();
        value=new int[(1<<(n+1))+1];

        al=new ArrayList[50001];
        for(int i=0;i<5000;i++)al[i]=new ArrayList<>();

        for(int i=1;i<=((1<<(n+1))-2);i++){
            value[i+1]=sc.nextInt();
            int u=i+1;
            int v=u/2;
            al[u].add(v);
            al[v].add(u);
        }
       ans=0;
       dfs(1,0);
       System.out.println(ans);

    }
}

class FastScanner{
    private int BUFFER_SIZE = 1 << 16;

   private  DataInputStream din;

   private  byte[] buffer;

   private int bufferPointer, bytesRead;

   public FastScanner() {
       din = new DataInputStream(System.in);
       buffer = new byte[BUFFER_SIZE];
       bufferPointer = bytesRead = 0;
   }

   public FastScanner( String file_name) throws IOException {
       din = new DataInputStream(new FileInputStream(file_name));
       buffer = new byte[BUFFER_SIZE];
       bufferPointer = bytesRead = 0;
   }

   public String readLine() throws IOException {
        byte[] buf = new byte[64];
       int cnt = 0, c;
       while ((c = read()) != -1) {
           if (c == '\n')
               break;
           buf[cnt++] = (byte) c;
       }
       return new String(buf, 0, cnt);
   }

   public String next() throws IOException{

       byte c = read();
       while(Character.isWhitespace(c)){
           c = read();
       }

        StringBuilder builder = new StringBuilder();
       builder.append((char)c);
       c = read();
       while(!Character.isWhitespace(c)){
           builder.append((char)c);
           c = read();
       }

       return builder.toString();
   }

   public int nextInt() throws IOException {
       int ret = 0;
       byte c = read();
       while (c <= ' ')
           c = read();
        boolean neg = (c == '-');
       if (neg)
           c = read();
       do {
           ret = ret * 10 + c - '0';
       } while ((c = read()) >= '0' && c <= '9');

       if (neg)
           return -ret;
       return ret;
   }

   public int[] nextIntArray( int n) throws IOException {
        int arr[] = new int[n];
       for(int i = 0; i < n; i++){
           arr[i] = nextInt();
       }
       return arr;
   }

   public long nextLong() throws IOException {
       long ret = 0;
       byte c = read();
       while (c <= ' ')
           c = read();
        boolean neg = (c == '-');
       if (neg)
           c = read();
       do {
           ret = ret * 10 + c - '0';
       } while ((c = read()) >= '0' && c <= '9');
       if (neg)
           return -ret;
       return ret;
   }

   public long[] nextLongArray( int n) throws IOException {
        long arr[] = new long[n];
       for(int i = 0; i < n; i++){
           arr[i] = nextLong();
       }
       return arr;
   }

   public char nextChar() throws IOException{
       byte c = read();
       while(Character.isWhitespace(c)){
           c = read();
       }
       return (char) c;
   }

   public double nextDouble() throws IOException {
       double ret = 0, div = 1;
       byte c = read();
       while (c <= ' ')
           c = read();
        boolean neg = (c == '-');
       if (neg)
           c = read();

       do {
           ret = ret * 10 + c - '0';
       } while ((c = read()) >= '0' && c <= '9');

       if (c == '.') {
           while ((c = read()) >= '0' && c <= '9') {
               ret += (c - '0') / (div *= 10);
           }
       }

       if (neg)
           return -ret;
       return ret;
   }

   public double[] nextDoubleArray( int n) throws IOException {
        double arr[] = new double[n];
       for(int i = 0; i < n; i++){
           arr[i] = nextDouble();
       }
       return arr;
   }

   private void fillBuffer() throws IOException {
       bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
       if (bytesRead == -1)
           buffer[0] = -1;
   }

   private byte read() throws IOException {
       if (bufferPointer == bytesRead)
           fillBuffer();
       return buffer[bufferPointer++];
   }

   public void close() throws IOException {
       if (din == null)
           return;
       din.close();
   }

}


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * User: Mikle
 * Date: 05.04.15
 * Time: 0:02
 * To change this template use File | Settings | File Templates.
 */
public class ZeptoB {

    public static int max(int a, int b)
    {   int m;
        if(a>=b)
            m=a;
        else
            m=b;
        return m;
    }
    public static void main(String[] args) {
        int i, j;

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int size = (int)Math.pow(2, n+1)-2;
        int paths_size = (int)Math.pow(2, n);
        int a[] = new int[size+1];
        for (i=1;i<=size;i++)
        {
            a[i]=sc.nextInt();
        }
        ArrayList<Integer> paths = new ArrayList<Integer>();
        int count=0;
        int x=n;
        int z;
        int count_j=0;
        int w;
        int divider=0;
    //   x=(int)Math.pow(2, n);
      for (j=n;j>0;j--)
     {
          z=(int)Math.pow(2, j);
          x=(int)Math.pow(2, j-1);

       // System.out.print(divider);
       // System.out.print(x);
        for (i=size-z+1;i<=size;i+=2)
        {

            paths.add(max(a[i], a[i+1]));
            count+=Math.abs(a[i]-a[i+1]);
        }

        size=size-z;
       if(j>1)
       {
           w=0;
        for (i=size-x+1;i<=size;i++)
        {
            a[i]+=paths.get(w);
          //  System.out.println(a[i]);
            w++;
        }
//System.out.print(j);
       }
         paths.clear();

      }
        System.out.println(count);
    }
}


import java.io.IOException;
import java.util.Scanner;

public class C {

    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        long c = in.nextLong();
        long hr = in.nextLong();
        long hb = in.nextLong();
        long wr = in.nextLong();
        long wb = in.nextLong();
        long sqr = (long) Math.sqrt(c) + 5;
        long ans = 0;
        for (int i = 0; i <= sqr; i++) {
            if (wb * i > c) {
                break;
            }
            ans = Math.max(ans, i * hb + (c - i * wb) / wr * hr);
        }
        for (int i = 0; i <= sqr; i++) {
            if (wr * i > c) {
                break;
            }
            ans = Math.max(ans, i * hr + (c - i * wr) / wb * hb);
        }
        System.out.println(ans);
        in.close();
    }

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class B {

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out);
        int nn = Integer.parseInt(in.readLine());
        int n = (1 << (nn + 1)) - 1;
        StringTokenizer st = new StringTokenizer(in.readLine());
        int[] a = new int[n];
        for (int i = 1; i < n; i++) {
            a[i] = Integer.parseInt(st.nextToken());
        }
        long max = 0;
        long[] path = new long[n];
        for (int i = 0; i < n; i++) {
            int ii = i;
            path[i] = a[0];
            while (ii != 0) {
                path[i] += a[ii];
                ii = (ii + 1) / 2 - 1;
            }
            max = Math.max(path[i], max);
        }
        long ans = 0;
        int L = (1 << nn) - 1;
        for (int j = nn; j >= 0; j--) {
            int step = (1 << j);
            long maxim = 0;
            for (int i = L; i < n; i++) {
                if (((i - L) % step) == 0 && i != L) {
                    if (maxim < max) {
                        for (int k = i - step; k < i; k++) {
                            path[k] += max - maxim;
                        }
                        ans += max - maxim;
                    }
                    maxim = 0;
                }
                maxim = Math.max(maxim, path[i]);
            }
        }
        out.println(ans);
        in.close();
        out.close();
    }

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class B {

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out);
        int nn = Integer.parseInt(in.readLine());
        int n = (int) Math.pow(2, nn + 1) - 1;
        StringTokenizer st = new StringTokenizer(in.readLine());
        int[] a = new int[n];
        for (int i = 1; i < n; i++) {
            a[i] = Integer.parseInt(st.nextToken());
        }
        int max = 0;
        int[] path = new int[n];
        for (int i = 0; i < n; i++) {
            int ii = i;
            path[i] = a[0];
            while (ii != 0) {
                path[i] += a[ii];
                ii = (ii + 1) / 2 - 1;
            }
            max = Math.max(path[i], a[0]);
        }
        int ans = 0;
        int L = (int) Math.pow(2, nn) - 1;
        for (int j = nn; j >= 0; j--) {
            int step = (int) Math.pow(2, j);
            int maxim = 0;
            for (int i = L; i < n; i++) {
                if (((i - L) % step) == 0 && i != L) {
                    if (maxim < max) {
                        for (int k = i - step; k < i; k++) {
                            path[k] += max - maxim;
                        }
                        ans += max - maxim;
                    }
                    maxim = 0;
                }
                maxim = Math.max(maxim, path[i]);
            }
        }
        out.println(ans);
        in.close();
        out.close();
    }

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class B {

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out);
        int nn = Integer.parseInt(in.readLine());
        int n = (1 << (nn + 1)) - 1;
        StringTokenizer st = new StringTokenizer(in.readLine());
        int[] a = new int[n];
        for (int i = 1; i < n; i++) {
            a[i] = Integer.parseInt(st.nextToken());
        }
        long max = 0;
        long[] path = new long[n];
        for (int i = 0; i < n; i++) {
            int ii = i;
            path[i] = a[0];
            while (ii != 0) {
                path[i] += a[ii];
                ii = (ii + 1) / 2 - 1;
            }
            max = Math.max(path[i], max);
        }
        long ans = 0;
        int L = (1 << nn) - 1;
        for (int j = nn; j >= 0; j--) {
            int step = (1 << j);
            long maxim = 0;
            for (int i = L; i <= n; i++) {
                if (((i - L) % step) == 0 && i != L) {
                    if (maxim < max) {
                        for (int k = i - step; k < i; k++) {
                            path[k] += max - maxim;
                        }
                        ans += max - maxim;
                    }
                    maxim = 0;
                }
                if (i == n) {
                    break;
                }
                maxim = Math.max(maxim, path[i]);
            }
        }
        out.println(ans);
        in.close();
        out.close();
    }

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CodeForces {

    private static final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    public static void main(String[] args) throws IOException {

        int levels = Integer.parseInt(in.readLine().trim());

        String[] lampCounts = in.readLine().trim().split(" ");

        Node[] nodeList = new Node[(int) (Math.pow(2, levels + 1) - 1)];

        nodeList[0] = new Node(0);
        for (int i = 1; i < nodeList.length; i++) {
            nodeList[i] = new Node(Integer.parseInt(lampCounts[i - 1]));
        }

        for (int i = 1; i < Math.pow(2, levels); i++) {
            nodeList[i - 1].setLeft(nodeList[2 * i - 1]);
            nodeList[i - 1].setRight(nodeList[2 * i]);
        }

        int newLights = 0;
        for (int i = (int) (Math.pow(2, levels) - 2); i >= 0; i--) {
            Node main = nodeList[i], left = main.getLeft(), right = main.getRight();
            Node minor = (left.getSum() < right.getSum()) ? left : right, major = (left.getSum() >= right.getSum()) ? left : right;

            int difference = Math.abs(left.getSum() - right.getSum()) / 2;

            if (minor.getValue() - major.getValue() < difference) {
                newLights += major.getValue() - minor.getValue() + difference;
                minor.setValue(major.getValue() + difference);
            } else if (minor.getValue() - major.getValue() > difference) {
                newLights += minor.getValue() - major.getValue() - difference;
                major.setValue(minor.getValue() - difference);
            }
        }

        System.out.println(newLights);
    }

    private static class Node {

        Node left, right;

        int value;

        public Node(int value) {
            this.value = value;
        }

        public Node getLeft() {
            return left;
        }

        public Node getRight() {
            return right;
        }

        public int getValue() {
            return value;
        }

        public int getSum() {
            int sum = 0;

            if (left != null) {
                sum += left.getSum() + left.getValue();
            }
            if (right != null) {
                sum += right.getSum() + right.getValue();
            }

            return sum;
        }

        public void setLeft(Node left) {
            this.left = left;
        }

        public void setRight(Node right) {
            this.right = right;
        }

        public void setValue(int value) {
            this.value = value;
        }
    }

}